【带权并查集】HDU 3047 Zjnu Stadium

http://acm.hdu.edu.cn/showproblem.php?pid=3047

【题意】

http://blog.csdn.net/hj1107402232/article/details/9921311

【Accepted】

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<cmath>
 6 #include<algorithm>
 7 #include<queue>
 8 #include<stack>
 9 #include<map>
10 using namespace std;
11 
12 int n,m;
13 const int maxn=5e4+2;
14 const int inf=0x3f3f3f3f;
15 int fa[maxn];
16 int rk[maxn];
17 void init()
18 {
19     for(int i=1;i<=n;i++)
20     {
21         fa[i]=i;
22     }
23 }
24 
25 int find(int x)
26 {
27     if(x==fa[x]) return  fa[x];
28     int fx=find(fa[x]);
29     rk[x]+=rk[fa[x]];
30     return fa[x]=fx;
31 }
32 
33 void mix(int x,int y,int d)
34 {
35     int fx=find(x);
36     int fy=find(y);
37     if(fx!=fy)
38     {
39         rk[fy]=rk[x]-rk[y]+d;
40         fa[fy]=fx;
41     }
42 }
43 
44 int query(int x,int y)
45 {
46     int fx=find(x);
47     int fy=find(y);
48     if(fx==fy)
49     {
50         return rk[y]-rk[x];
51     }
52     else
53     {
54         return inf;
55     }
56 }
57 
58 int main()
59 {
60     while(~scanf("%d%d",&n,&m))
61     {
62         init();
63         memset(rk,0,sizeof(rk));
64         int A,B,x;
65         int cnt=0;
66         for(int i=0;i<m;i++)
67         {
68             scanf("%d%d%d",&A,&B,&x);
69             int d=query(A,B);
70             if(d==inf) 
71             {
72                 mix(A,B,x);
73             }
74             else if(d!=x)
75             {
76                 cnt++;
77             }
78         }
79         printf("%d\n",cnt);
80     }
81     return 0;
82 }
带权并查集

 

转载于:https://www.cnblogs.com/itcsl/p/7261009.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值