杭电 HOJ 3038 How Many Answers Are Wrong 解题报告
并查集好题。看代码吧,相信你会理解的
#include <iostream> using namespace std; int root[200001],sum[200001],data,ans; int find(int x) { if(root[x]==-1) return x; int t=root[x]; root[x]=find(root[x]); sum[x]+=sum[t]; return root[x]; } void unio(int x,int y) { int rootx=find(x); int rooty=find(y); if(rootx==rooty) { if(sum[y]!=sum[x]+data) ans++; return; } if(rootx>rooty) { sum[rootx]=sum[y]-sum[x]-data; root[rootx]=rooty; } else { sum[rooty]=sum[x]+data-sum[y]; root[rooty]=rootx; } } int main() { int n,m,i,x,y; while(~scanf("%d%d",&n,&m)) { ans=0; memset(sum,0,4*n+4); memset(root,-1,4*n+4); for(i=0;i<m;i++) { scanf("%d%d%d",&x,&y,&data); unio(x-1,y); } printf("%d\n",ans); } }