题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3038
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<queue> 6 #include<stdlib.h> 7 #include<map> 8 #include<cmath> 9 10 using namespace std; 11 12 #define N 250000 13 #define INF 0x3f3f3f3f 14 15 int a[N], f[N]; 16 17 int Find(int x) 18 { 19 if(f[x] != x) 20 { 21 int p=f[x]; 22 f[x]=Find(f[x]); 23 a[x]+=a[p]; 24 } 25 return f[x]; 26 } 27 28 int main() 29 { 30 int m,n,i,b,c,s; 31 32 while(scanf("%d%d", &n,&m) != EOF) 33 { 34 memset(a,0,sizeof(a)); 35 for(i=0;i<=n;i++) 36 f[i]=i; 37 38 int ans=0; 39 for(i=0;i<m;i++) 40 { 41 scanf("%d%d%d", &b,&c,&s); 42 b--; 43 int x=Find(b); 44 int y=Find(c); 45 if(x != y) 46 { 47 f[y]=x; 48 a[y]=a[b]+s-a[c]; 49 } 50 else 51 { 52 if(a[c]-a[b] != s) 53 ans++; 54 } 55 } 56 printf("%d\n", ans); 57 } 58 return 0; 59 }