题目链接:点我点我
题意:
题解:
两题代码差不多,放个3047的。
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 using namespace std; 5 6 const int N=200010; 7 int Father[N],value[N]; 8 9 int find(int x){ 10 if(x==Father[x]) return x; 11 int tmp=Father[x]; 12 Father[x]=find(Father[x]); 13 value[x]+=value[tmp]; 14 return Father[x]; 15 } 16 17 int Union(int x,int y,int len){ 18 int fx=find(x),fy=find(y); 19 if(fx==fy){ 20 if(value[x]+len!=value[y]) return 0; 21 return 1; 22 } 23 Father[fy]=fx; 24 value[fy]=value[x]-value[y]+len; 25 return 1; 26 } 27 28 int main(){ 29 int n,m; 30 int a,b,c; 31 while(scanf("%d %d",&n,&m)!=EOF){ 32 int ans=0; 33 for(int i=0;i<=n;i++) value[i]=0,Father[i]=i; 34 for(int i=1;i<=m;i++){ 35 scanf("%d %d %d",&a,&b,&c); 36 if(!Union(a,b,c)) ans++; 37 } 38 printf("%d\n",ans); 39 } 40 return 0; 41 }
时间: 2024-11-06 16:44:40