牛客小白月赛24 H--人人都是好朋友(并查集+离散化/unordered_map)

地址:https://ac.nowcoder.com/acm/contest/5158/H

 

 

     解析:1e9,开不了这么大的pr[],所以采取离散化处理。假设输入了 10  12 ,可以把它们存到另一个数组now[]里:i=1,10  i=2,12,这样就可以把数字用坐标来代替,n只有1e6,所以pr[]开到2e6往上就可以了。使用了lower_bound来查找数字的对应位置。unordered_map也可以做,但是我的编译器报错,所以就没这么写,先插个眼吧:

unordered_map<int,int>father;

        然后是我的离散化代码:

#include<iostream>
#include<cstdio>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=3e6;
ll pr[maxn],a[maxn],b[maxn],c[maxn];
ll tot=1;
ll now[maxn];
void init()
{
    for(int i = 1 ; i  <= tot ; i++)
    {
        pr[i]=i;
    }
}
ll find(ll  x)
{
    if(x!=pr[x])
        return pr[x]=find(pr[x]);
        return x;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        tot=1;
        for(int i = 1 ; i <= n ; i++)
        {
            scanf("%lld%lld%lld",&a[i],&b[i],&c[i]);
            now[tot++]=a[i];
            now[tot++]=b[i];
        }
        sort(now+1,now+tot+1);
        init();
        int ok = 0 ;
        for(int i = 1 ; i <= n ; i++)
        {
            ll x=lower_bound(now+1,now+tot+1,a[i])-now;
            ll y=lower_bound(now+1,now+tot+1,b[i])-now;                
            ll fa=find(x);
            ll fb=find(y);
            if(c[i]==1)
            {
                if(fa!=fb)
                    pr[fa]=fb;
            }
            else
            {
                if(fa==fb)
                {
                    ok=1;break;
                }
            }
        }
        if(!ok)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
}

 

posted @ 2020-04-26 00:19  liyexin  阅读(210)  评论(0编辑  收藏  举报