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.
InputThere 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.
OutputFor 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
HintHint:
(PS: the 5th and 10th requests are incorrect)
就是在一个圆形的桌子上坐着,现在给你n,m两个数分别表示n个人m组数据,每组数据包含x,y,s,分别表示x距离y为s,然后让你判断有几个数据是不合法的
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int pre[50050];
int sum[50050];//表示到节点的距离
int mod=300;//圆形坐着一旦距离大于300就是又一圈开始了
int root(int x)
{
if(x!=pre[x])
{
int s=pre[x];
pre[x]=root(s);
sum[x]=(sum[x]+sum[s])%mod;//因为可能出现相减为负值的情况
} //每次更新到祖先节点的距离
return pre[x];
}
bool xia(int x,int y,int z)
{
int xx=root(x);
int yy=root(y);
if(xx!=yy)
{
pre[yy]=xx;
sum[yy]=(sum[x]-sum[y]+z+mod)%mod;//两个祖先节点不等就更新 新的祖先节点的位置
}
else
{
if(sum[y]!=(sum[x]+z)%mod) return true;
}// 说明两个节点的公共祖先是相同的,如果现在的距离和以前的不一样了,那说明也是不行的
// 比如说1-2是40;3-4是20;那么现在有了1-3为10;把这三个节点连一起后
// 4-2的距离就是40-20+10=30;
return 0;
}
int main()
{
int n,m,s,x,y;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
{
pre[i]=i;
sum[i]=0;
}
int ans=0;
while(m--)
{
scanf("%d%d%d",&x,&y,&s);
if(xia(x,y,s))
ans++;
}
printf("%d\n",ans);
}
}