首页 > 代码库 > hdu 3038 How Many Answers Are Wrong

hdu 3038 How Many Answers Are Wrong

http://acm.hdu.edu.cn/showproblem.php?pid=3038

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define maxn 600000
 5 using namespace std;
 6 
 7 int f[maxn],d[maxn];
 8 int ans;
 9 int n,m;
10 
11 int find1(int x)
12 {
13     if(x==f[x]) return x;
14     int f1=f[x];
15     f[x]=find1(f[x]);
16     d[x]+=d[f1];
17     return f[x];
18 }
19 
20 void  union1(int a,int b,int x)
21 {
22     int fa=find1(a);
23     int fb=find1(b);
24     if(fa!=fb)
25     {
26         f[fb]=fa;
27         d[fb]=d[a]+x-d[b];
28         return;
29     }
30     if(fa==fb)
31     {
32         if(d[b]-d[a]!=x) ans++;
33     }
34 }
35 
36 void inti()
37 {
38     for(int i=0; i<=n; i++)
39     {
40         f[i]=i;
41     }
42     memset(d,0,sizeof(d));
43     ans=0;
44 }
45 
46 int main()
47 {
48     int a1,b1,x1;
49     while(scanf("%d%d",&n,&m)!=EOF)
50     {
51         inti();
52         for(int i=1; i<=m; i++)
53         {
54             scanf("%d%d%d",&a1,&b1,&x1);
55             a1--;
56             union1(a1,b1,x1);
57         }
58         printf("%d\n",ans);
59     }
60     return 0;
61 }
View Code