51nod 1515 明辨是非(合并并查集)

题目来源: 原创
基准时间限制:1 秒 空间限制:131072 KB 分值: 160  难度:6级算法题
 收藏
 关注

给n组操作,每组操作形式为x y p。

当p为1时,如果第x变量和第y个变量可以相等,则输出YES,并限制他们相等;否则输出NO,并忽略此次操作。

当p为0时,如果第x变量和第y个变量可以不相等,则输出YES,并限制他们不相等 ;否则输出NO,并忽略此次操作。

Input
输入一个数n表示操作的次数(n<=1*10^5)
接下来n行每行三个数x,y,p(x,y<=1*10^8,p=0 or 1)
Output
对于n行操作,分别输出n行YES或者NO
Input示例
3
1 2 1
1 3 1
2 3 0
Output示例
YES
YES
NO





#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<map>
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6+10;
typedef long long LL;
const LL mod = 1e9+7;
const int inf = 0x3f3f3f3f;
unordered_map<int,int>q;
int f[N];
set<int>dict[N];
int get(int x)
{
    if(f[x]==x) return x;
    f[x]=get(f[x]);
    return f[x];
}


int main()
{
    q.clear();
    int n, k=1;
    scanf("%d", &n);
    for(int i=0;i<=2*n;i++) f[i]=i;
    for(int i=0;i<n;i++)
    {
        int x, y, p;
        scanf("%d %d %d", &x, &y, &p);
        if(!q.count(x)) q[x]=k++;
        if(!q.count(y)) q[y]=k++;
        int a=q[x],b=q[y];
        int t1=get(a), t2=get(b);
        if(p==1)
        {
            if(t1==t2) puts("YES");
            else if(dict[t1].count(t2)) puts("NO");
            else
            {
                puts("YES");
                if(dict[t1].size()>dict[t2].size()) swap(t1,t2);
                f[t1]=t2;
                set<int> ::iterator it;
                for(it=dict[t1].begin();it!=dict[t1].end();it++)
                {
                    dict[t2].insert(*it);
                    dict[*it].erase(t1);
                    dict[*it].insert(t2);
                }
            }
        }
        else
        {
            if(t1==t2) puts("NO");
            else
            {
                puts("YES");
                if(!dict[t1].count(t2))  dict[t1].insert(t2),dict[t2].insert(t1);
            }
        }
    }
    return 0;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值