一个环形体育场,座位为环形,一圈有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;
}