bzoj4195 (union search + discretization)

The gist of the title: Given the equality or inequality relationship of n variables with each other, find out whether these relationships are contradictory

Idea: Add equal variables to the set and check whether the unequal query is legal

eg: The data is large and discretized (however I use map)

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<map>
using namespace std;
int fa[10000000],n,sum[10000000],tot,T;
map<int,int> old,tong;
struct node
{
    int x,y,c;
}a[10000000];
template<class T>void read(T &x)
{
    x=0;char ch=getchar();
    while(ch<'0'||ch>'9')  ch=getchar();
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
}
int find(int x)
{
    int p=x,q;
    while(x!=fa[x])
      x=fa[x];
    while(p!=x)
    {
        q = fa [p];
        fa [p] = x;
        p = q
    }
    return x;
}
intmain ()
{
    read(T);
    while(T--)
    {
        old.clear();tong.clear();tot=0;bool flag=0;
        read(n);
        for(int i=1;i<=n;i++)
        {
            read(a[i].x);read(a[i].y);read(a[i].c);
            if(tong[a[i].x]==0)
            {   
                tong[a[i].x]=1;
                sum [ ++ tot] = a [i] .x;
            }
            if(tong[a[i].y]==0)
            {
                tong[a[i].y]=1;
                sum [ ++ tot] = a [i] .y;
            }   
        }
        sort(sum+1,sum+1+tot); 
        for(int i=1;i<=tot;i++) old[sum[i]]=i;
        for(int i=1;i<=n;i++)
        {
            a[i].x=old[a[i].x];
            a[i].y=old[a[i].y];
        }       
        for(int i=1;i<=tot;i++) fa[i]=i; 
        for(int i=1;i<=n;i++)
        {
            int p=find(a[i].x),q=find(a[i].y);
            if(a[i].c==1&&p!=q) fa[p]=q;
            if(a[i].c!=1&&p==q){flag=1;break;}
        }
        if(flag==1){printf("NO\n");continue;}
        for(int i=1;i<=n;i++)
        {
            int p=find(a[i].x),q=find(a[i].y);
            if(a[i].c==1&&p!=q){flag=1;break;}
            if(a[i].c==0&&p==q){flag=1;break;}
        }
        if(flag==1)printf("NO\n");
        else printf("YES\n");
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325304910&siteId=291194637