[Bzoj4195] [NOI2015] 程序自动分析 [并查集,哈希,map] 题解

用并查集+离散化,注意:并查集数组大小不是n而是n*2

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 #include <cstring>
 6 #include <cmath>
 7 #include <ctime>
 8 #include <map>
 9 
10 using namespace std;
11 
12 int    fa[2100000],a[1100000],b[1100000],op[1100000];
13 
14 inline    int    get_anc(const int x)
15 {
16     return fa[x]==x ? x:fa[x]=get_anc(fa[x]);
17 }
18 
19 int main()
20 {
21     int    i,n,q,S,T,cnt=0;
22 
23     scanf("%d",&q);
24     while(q--)
25     {
26         scanf("%d",&n);
27         map<int,int>    Map;
28         Map.clear();cnt=0;
29         for(i=1;i<=n<<1;++i)fa[i]=i;
30         
31         for(i=1;i<=n;++i)scanf("%d%d%d",&a[i],&b[i],&op[i]);
32 
33         for(i=1;i<=n;++i)
34         {
35             if(op[i])
36             {
37                 if(!Map[a[i]])Map[a[i]]=++cnt;
38                 if(!Map[b[i]])Map[b[i]]=++cnt;
39                 int x=Map[a[i]],y=Map[b[i]];
40                 S=get_anc(x),T=get_anc(y);
41                 if(S!=T)fa[S]=T;
42             }
43         }
44 
45         for(i=1;i<=n;++i)
46         {
47             if(!op[i])
48             {
49                 if(!Map[a[i]])Map[a[i]]=++cnt;
50                 if(!Map[b[i]])Map[b[i]]=++cnt;
51                 int x=Map[a[i]],y=Map[b[i]];
52                 S=get_anc(x),T=get_anc(y);
53                 if(S==T)
54                 {
55                     printf("NO\n");
56                     goto Fail;
57                 }
58             }
59         }
60         
61         printf("YES\n");
62 Fail:;
63     }
64 
65     return 0;
66 }
View Code

 

转载于:https://www.cnblogs.com/Gster/p/4977879.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值