51nod 1515 right from wrong

Subject description:

$ $ A n-operation group, the operation of each form xyp.
When $ p $ 1, if the first variable $ x $ and $ y $ variables can be equal, output YES, and limit their
equal; otherwise the output NO, and ignore the operation.
When $ p $ 0, if the first variable $ x $ and $ y $ variables can be equal, output YES, and restrict him
are equal; otherwise the output NO, and ignore the operation.

Ideas:

See maintain equal relations, it is natural to think disjoint-set.

But this question to maintain equal and unequal relations, common disjoint-set can not meet.

After how to do it? In the examination room I was ignorant of the force. Later found with a set of violence and safeguard each check can not be equal and who would be finished within the set. Good mentally ah! I really still too dishes.

May find fewer number of elements in a set at the time of the merger equal relationship, he will be directly inserted in another set. Such violence is called heuristic merge. Clever but useless

When it merges directly into the unequal relationship set in just fine.

Code:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
using namespace std;
set<int>s[2000005];
set<int>::iterator it;
map<int,int>a;
int f[2000005];
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
int main()
{
//    freopen("TrueFalse.in","r",stdin);
//    freopen("TrueFalse.out","w",stdout);
    int n;
    scanf("%d",&n);
    int i,cnt=0;
    for(i=1;i<=n*2;i++)
        f[i]=i;
    for(i=1;i<=n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        a[x]?(x=a[x]):(x=a[x]=++cnt);
        a[y]?(y=a[y]):(y=a[y]=++cnt);
        int opt;
        scanf("%d",&opt);
        int u=find(x);
        int v=find(y);
        if(opt==1)
        {
            if(s[u].count(v))
                puts("NO");
            else if(u!=v)
            {
                if(s[u].size()>s[v].size())
                    swap(u,v);
                f[u]=v;
                for(it=s[u].begin();it!=s[u].end();it++)
                {
                    s[*it].erase(u);
                    s[*it].insert(v);
                    s[v].insert(*it);
                }
                puts("YES");
            }
            else
                puts("YES");
        }
        else
        {
            if(u==v)
                puts("NO");
            else
            {
                s[u].insert(v);
                s[v].insert(u);
                puts("YES");
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/handsome-wjc/p/11291247.html