http://acm.hdu.edu.cn/showproblem.php?pid=3038 #include<iostream> using namespace std; #define N 200001 int a,b,k; struct node{ int father; int len; }p[N]; void init(int n){ for(int i=0;i<=n;i++){ p[i].father=i; p[i].len=0; } } int find(int x){ if(x==p[x].father) return p[x].father; int r=find(p[x].father); p[x].len+=p[p[x].father].len; return p[x].father=r; } bool merge(int x,int y){ int fx=find(x); int fy=find(y); if(fx==fy) return p[y].len-p[x].len!=k; p[fy].father=fx; p[fy].len=p[x].len-p[y].len+k; return false; } int main(void){ int n,m; while(~scanf("%d%d",&n,&m)){ int c=0; init(n); while(m--){ scanf("%d%d%d",&a,&b,&k); a--; if(merge(a,b)) c++; } printf("%d/n",c); } }