hdu 3047:Zjnu Stadium

一个环形体育场,座位为环形,一圈有300个座位。有n个人,分别编号1~n,需要满足m个条件,格式为“A B X”,意为B距离A顺时针X个座位。问有几个条件不符合。

 

带权并查集。要注意的是用以往的风格写get_root函数会错,比如说

   dis[i] += dis[fa[i]] ;

   return fa[i] = find(fa[i]) ;

这样就错了,因为例如5-> 4 -> 3 -> 2 -> 1,此时fa[5]指向4,故dis[5]会加上4~3之间的距离,而不是4~1之间的距离。所以应该用下面的方式写

   int temp ;

   temp = fa[x] ;

   fa[x] = get_root(fa[x]) ;

   dis[x] += dis[temp] ;

    return fa[x] ;


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int MAXN = 50005 ;
int fa[MAXN] , dis[MAXN] ;
int ans = 0 ;

int get_root(int x) {
    if (x == fa[x]) {
        return x ;
    }
    else {
        int temp ;
        temp = fa[x] ;
        fa[x] = get_root(fa[x]) ;
        dis[x] += dis[temp] ;
        return fa[x] ;
    }
}

void Union(int x , int y , int distance) {
    int root_x , root_y ;
    root_x = get_root(x) ;
    root_y = get_root(y) ;
    if (root_x == root_y) {
        if ((dis[x] + distance) != dis[y])
            ans ++ ;
    }
    else {
        fa[root_y] = root_x ;
        dis[root_y] = dis[x] + distance - dis[y] ;
    }
}

int main() {
    //freopen("in.txt" , "r" , stdin) ;
    int n , m ;
    while (scanf("%d%d" , &n , &m) != EOF) {

        ans = 0 ;
        int i ;
        for (i = 0 ; i <= n ; i ++) {
            fa[i] = i ; dis[i] = 0 ;
        }

        while (m --) {
            int a , b , x ;
            cin >> a >> b >> x ;
            Union(a , b , x) ;
        }

        cout << ans << endl ;
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值