Zjnu Stadium
TimeLimit: 2000/1000 MS (Java/Others) Memory Limit:32768/32768 K (Java/Others)
Total Submission(s): 4759 Accepted Submission(s): 1836
ProblemDescription
In 12th Zhejiang College Students Games2007, there was a new stadium built in Zhejiang Normal University. It was amodern stadium which could hold thousands of people. The audience Seats made acircle. The total number of columns were 300 numbered 1--300, countedclockwise, we assume the number of rows were infinite.
These days, Busoniya want to hold a large-scale theatrical performance in thisstadium. There will be N people go there numbered 1--N. Busoniya has Reservedseveral 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 peoplenumbered A. For example: A is in column 4th and X is 2, then B must in column6th (6=4+2).
Now your task is to judge weather the request is correct or not. The rule ofyour judgement is easy: when a new request has conflicts against the foregoingones then we define it as incorrect, otherwise it is correct. Please find outall the incorrect requests and count them as R.
Input
There aremany test cases:
For every case:
The first line has two integer N(1<=N<=50,000), M(0<=M<=100,000),separatedby 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.
SampleInput
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
SampleOutput
2
Hint
Hint:
(PS: the 5thand 10th requests are incorrect)
Source
2009Multi-University Training Contest 14 - Host by ZJNU
Recommend
gaojie | Wehave carefully selected several similar problems for you: 3172 3038 3045 3046 3049
算法分析:
难点在于:求节点到根的距离。
求到跟的距离dist[a] += dist[tem]; dist[rb]=dist[a]+x-dist[b];注意这两行代码,这是核心代码,首先第一行是求出节点a到根的距离。第二行代码使用的是数学中向量计算的原理如图[宋1]
图意:
始终以ra点作为祖先点,如果每次读入时a,b的祖先不相同的话,那么就把b连到a的祖先即为ra上去,别忘了还要更新b的根节点到ra的距离,我们只改变rb到ra的距离,至于b到ra的距离,这里我们可以在find祖先时,通过路径压缩来改变(dist[a] += dist[tem])。
那么距离根据向量法则可得为:dis[rb]=dis[b]-dis[a]+x;
当dis[rb]-dis[ra]!=x时,那么就是不符合条件的说法了。
代码实现:
#include<bits/stdc++.h>
using namespace std;;
#define N 50005
int fa[N],dis[N];
int find(int x)
{
if(x==fa[x])
return x;
int t=fa[x];
fa[x]=find(fa[x]);
dis[x]+=dis[t]; //节点a到根的距离
return fa[x];
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
{fa[i]=i;dis[i]=0;}
int ans=0;
for(int i=1;i<=m;i++)
{
int a,b,x;
scanf("%d%d%d",&a,&b,&x);
int r1=find(a),r2=find(b);
if(r1==r2)
{
if(dis[b]-dis[a]!=x) ans++;//有重复位置,错误
}
else
{
fa[r2]=r1;
dis[r2]=dis[a]+x-dis[b];//求r2与父亲节点的距离
}
}
printf("%d\n",ans);
}
return 0;
}