hdu3038 How Many Answers Are Wrong 种类并查集

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int n, m;
 7 const int maxn = 200005;
 8 int fa[maxn];
 9 int sum[maxn];
10 
11 int Find(int x){
12     if (x == fa[x])
13         return x;
14     else{
15         int t = fa[x];
16         fa[x] = Find(fa[x]);
17         sum[x] += sum[t];
18         return fa[x];
19     }
20 }
21 
22 bool Set_Union(int x, int y, int s){
23     int fx = Find(x);
24     int fy = Find(y);
25     if (fx == fy && sum[x] != sum[y] + s)
26         return false;
27     else if(fx != fy){
28         if (fx > fy){
29             fa[fy] = fx;
30             sum[fy] = sum[x] - s - sum[y];
31         }
32         else{
33             fa[fx] = fy;
34             sum[fx] = s + sum[y] - sum[x];
35         }
36     }
37     return true;
38 }
39 
40 void init(){
41     memset(sum, 0, sizeof(sum));    //必须初始化为零
42     for (int i = 0; i <= n; i++){
43         fa[i] = i;
44     }
45 }
46 
47 int main(){
48     while (scanf("%d %d", &n, &m) != EOF){
49         init();        //初始化
50         int ans = 0;
51         while (m--){
52             int a, b, s;
53             scanf("%d%d%d", &a, &b, &s);
54             a--;
55             if (!Set_Union(a, b, s)){
56                 ans++;
57             }
58         }
59         printf("%d\n", ans);
60     }
61     //system("pause");
62     return 0;
63 }

 

转载于:https://www.cnblogs.com/ouyang_wsgwz/p/7464986.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值