【NOI2015】程序自动分析(并查集)

传送门

开始想错了,写了个种类并查集

结果发现可能会有很多个种类

便直接离线做

先把所有相等的 m e r g e merge 在一起

然后再处理不等的

如果有不等关系的在同一个联通块中,显然是不行的

不想离散化便直接上 m a p map

m a p map 大法好啊

#include<bits/stdc++.h>
#include<tr1/unordered_map>
using namespace std;
inline int read(){
    char ch=getchar();
    int res=0;
    while(!isdigit(ch))ch=getchar();
    while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48),ch=getchar();
    return res;
}
const int N=1000006;
tr1::unordered_map<int,int> fa;
struct opr{
    int u,v;
}p[N];
int flag,n,cnt;
inline int find(int x){
    return fa[x]==x?fa[x]:fa[x]=find(fa[x]);
}
int main(){
    int T=read();
    while(T--){
        n=read();cnt=0;fa.clear();
        for(int i=1;i<=n;i++){
            int u=read(),v=read(),op=read();
            if(!fa[u])fa[u]=u;if(!fa[v])fa[v]=v;
            if(op==1){
                int f1=find(u),f2=find(v);
                if(f1!=f2)fa[f1]=f2;
            }
            else p[++cnt].u=u,p[cnt].v=v;
        }
        int i;
        for(i=1;i<=cnt;++i){
            if(find(p[i].u)==find(p[i].v))break;
        }
        if(i==cnt+1)cout<<"YES"<<'\n';
        else cout<<"NO"<<'\n';
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42555009/article/details/85345025
今日推荐