1. 程式人生 > 實用技巧 >Luogu P1955 [NOI2015]程式自動分析

Luogu P1955 [NOI2015]程式自動分析

思路

這個題要是資料範圍小的話那就可以是黃題或者綠題了。但是,良心的出題人偏偏要把資料範圍搞得那麼大、、無語……

這個題就是在把資料離散化之後,在把1的情況全部丟進並查集裡,特判關於0的情況即可(這裡可以離散化的原因是我們並不需要這些資料的真實大小,只需要知道它們的相對大小即可)。

Code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define MAXN 1000005
int t, n, f[MAXN];
int c[MAXN << 1];
struct node{
    int x, y, e;
} inp[MAXN];
bool cmp(const node a,const node b){
    return a.e > b.e;
}
inline int get_father(int k){
    return f[k] == k ? k : f[k] = get_father(f[k]);
}
int main(){
    scanf("%d", &t);
    while(t--){
        int cnt = 0;
        memset(f, 0, sizeof(f));
        memset(c, 0, sizeof(c));
        scanf("%d", &n);
        for (int i = 1; i <= n;++i){
            scanf("%d%d", &inp[i].x, &inp[i].y);
            scanf("%d", &inp[i].e);
            c[++cnt] = inp[i].x, c[++cnt] = inp[i].y;
        }
        std::sort(c + 1, c + cnt + 1);
        int tot = std::unique(c + 1, c + cnt + 1) - c - 1;
        for (int i = 1; i <= n;++i){
            inp[i].x = std::lower_bound(c + 1, c + tot + 1, inp[i].x) - c;
            inp[i].y = std::lower_bound(c + 1, c + tot + 1, inp[i].y) - c;
        }
        for (int i = 1; i <= MAXN;++i)
            f[i] = i;
//        std::sort(inp + 1, inp + tot + 1, cmp);
        int flag = 1;
        for (int i = 1; i <= n;++i){
            int p = get_father(inp[i].x), q = get_father(inp[i].y);
            if(inp[i].e==1&&p!=q)f[p] = q;
        }
        for (int i = 1; i <= n;++i){
            int p = get_father(inp[i].x), q = get_father(inp[i].y);
            if(inp[i].e==0&&p==q){
                flag = 0;
                puts("NO");
                break;
            }
        }
        if (flag)  puts("YES");
    }
    return 0;
}