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 10
1 2 150
3 4 200
1 5 270
2 6 200
6 5 80
4 7 150
8 9 100
4 8 50
1 7 100
9 2 100
Sample Output
2
题意
就是在一个圆形的桌子上坐着,现在给你n,m两个数分别表示n个人m组数据,每组数据包含x,y,s,分别表示x距离y为s,然后让你判断有几个数据是不合法的(很显然,用加权并查集呀)
代码
#include<stdio.h>
#include<string.h>
int f[51234];
int s[51234];
int find(int x)
{
if(x!=f[x])
{
int t=f[x];
f[x]=find(f[x]);
s[x]=(s[x]+s[t])%300; //每次更新到祖先节点的距离
}
return f[x];
}
int merge(int x,int y,int z)
{
int t1=find(x);
int t2=find(y);
if(t1!=t2)//两个祖先节点不等就更新 新的祖先节点的位置
{
f[t2]=t1;
s[t2]=(s[x]-s[y]+z+300)%300;//因为可能出现相减为负值的情况 所以加个300
}
else
{
if(s[y]!=(s[x]+z)%300)// 说明两个节点的公共祖先是相同的,如果现在的距离和以前的不一样了,就是错的
return 1;
}
return 0;
}
int main()
{
int n,m,x,y,z,i;
while(~scanf("%d%d",&n,&m))
{
for(i=1;i<=n;i++)
{
f[i]=i;
s[i]=0;
}
int g=0;
while(m--)
{
scanf("%d%d%d",&x,&y,&z);
if(merge(x,y,z))
g++;
}
printf("%d\n",g);
}
}