首页 > 代码库 > hdu 3074 Zjnu Stadium (带权并查集)

hdu 3074 Zjnu Stadium (带权并查集)

Zjnu Stadium

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1744    Accepted Submission(s): 660


Problem Description
In 12th Zhejiang College Students Games 2007, there was a new stadium built in Zhejiang Normal University. It was a modern stadium which could hold thousands of people. The audience Seats made a circle. The total number of columns were 300 numbered 1--300, counted clockwise, we assume the number of rows were infinite.
These days, Busoniya want to hold a large-scale theatrical performance in this stadium. There will be N people go there numbered 1--N. Busoniya has Reserved several seats. To make it funny, he makes M requests for these seats: A B X, which means people numbered B must seat clockwise X distance from people numbered A. For example: A is in column 4th and X is 2, then B must in column 6th (6=4+2).
Now your task is to judge weather the request is correct or not. The rule of your judgement is easy: when a new request has conflicts against the foregoing ones then we define it as incorrect, otherwise it is correct. Please find out all the incorrect requests and count them as R.
 

 

Input
There are many test cases:
For every case: 
The first line has two integer N(1<=N<=50,000), M(0<=M<=100,000),separated by a space.
Then M lines follow, each line has 3 integer A(1<=A<=N), B(1<=B<=N), X(0<=X<300) (A!=B), separated by a space.

 

 

Output
For every case: 
Output R, represents the number of incorrect request.
 

 

Sample Input
10 101 2 1503 4 2001 5 2702 6 2006 5 804 7 1508 9 1004 8 501 7 1009 2 100
 

 

Sample Output
2
Hint
Hint:(PS: the 5th and 10th requests are incorrect)
 

 

Source
2009 Multi-University Training Contest 14 - Host by ZJNU

 

提议很简单,就是问:

     a和b是否在同一个集合,不在就将他们加入到集合,在就对他们进行路径比较,如果给定的路程和实际路程不一样,那就表示冲突,记录下来

输出最后冲突的数量。(注意的是,b在a的前面,也就是b到根的路程要大于a到根的路程)

 

---------》带权值的路径......

代码:

    

 1 #include<stdio.h> 2 #include<stdlib.h> 3 #define maxn 50005 4  5  int father[maxn]; 6  int dist[maxn]; 7  int n,m,re; 8  9 void  init(){10       re=0;11   for(int i=0;i<=n;i++){12       father[i]=i;13       dist[i]=0;14     }15  }16 17  int fin(int x){18      if(x==father[x]) return x;19      int pre=father[x];20      father[x]=fin(father[x]);21      dist[x]+=dist[pre]; //统计每一个点到根点的距离22      return father[x];23  }24 25  void Union(int x , int y , int val ){26      int a=fin(x);27      int b=fin(y);28      if(a==b){29     //注意方向-------顺时针30       if(dist[y]-dist[x]!=val)31             re++;32     }33     else{34         father[b]=a;35         dist[b]=dist[x]-dist[y]+val;36     }37  }38 39 int main(){40      int a,b,c;41    while(scanf("%d%d",&n,&m)!=EOF){42       init();43    while(m--){44       scanf("%d%d%d",&a,&b,&c);45          Union(a,b,c);46    }47       printf("%d\n",re);48 }49   return 0;50 }
View Code

 

  

hdu 3074 Zjnu Stadium (带权并查集)