1. 程式人生 > >【帶權並查集】HDU 3047 Zjnu Stadium

【帶權並查集】HDU 3047 Zjnu Stadium

void mem ios ack string blank iostream style csdn

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

【題意】

http://blog.csdn.net/hj1107402232/article/details/9921311

【Accepted】

技術分享
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<cmath>
 6 #include<algorithm>
 7 #include<queue>
 8 #include<stack>
 9
#include<map> 10 using namespace std; 11 12 int n,m; 13 const int maxn=5e4+2; 14 const int inf=0x3f3f3f3f; 15 int fa[maxn]; 16 int rk[maxn]; 17 void init() 18 { 19 for(int i=1;i<=n;i++) 20 { 21 fa[i]=i; 22 } 23 } 24 25 int find(int x) 26 { 27 if(x==fa[x]) return fa[x];
28 int fx=find(fa[x]); 29 rk[x]+=rk[fa[x]]; 30 return fa[x]=fx; 31 } 32 33 void mix(int x,int y,int d) 34 { 35 int fx=find(x); 36 int fy=find(y); 37 if(fx!=fy) 38 { 39 rk[fy]=rk[x]-rk[y]+d; 40 fa[fy]=fx; 41 } 42 } 43 44 int query(int x,int y) 45 { 46 int
fx=find(x); 47 int fy=find(y); 48 if(fx==fy) 49 { 50 return rk[y]-rk[x]; 51 } 52 else 53 { 54 return inf; 55 } 56 } 57 58 int main() 59 { 60 while(~scanf("%d%d",&n,&m)) 61 { 62 init(); 63 memset(rk,0,sizeof(rk)); 64 int A,B,x; 65 int cnt=0; 66 for(int i=0;i<m;i++) 67 { 68 scanf("%d%d%d",&A,&B,&x); 69 int d=query(A,B); 70 if(d==inf) 71 { 72 mix(A,B,x); 73 } 74 else if(d!=x) 75 { 76 cnt++; 77 } 78 } 79 printf("%d\n",cnt); 80 } 81 return 0; 82 }
帶權並查集

【帶權並查集】HDU 3047 Zjnu Stadium