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
Hint
Hint:
(PS: the 5th and 10th requests are incorrect)
题意:
在一个很大体育馆里,有300列的座位,行数无限,最初已知根距离值默认0,其他座位最初距离根位置未知,有一个操作 A B X,意思是A B座位同根,并且B距离根距离相对于A大X,dist[B]=dist[A]+X;
给你一些这样形式的信息,问不正确有多少?
不正确的信息一定是当前与前面已知信息冲突,
比如 A ,B X 满足冲突条件是 A B,在已经有同根的关系下,并且dist[B]-distp[A] !=X 就冲突。
然后就是注意在 路劲压缩的时候这种关系的传递该怎么写。
首先找祖先的操作,x直接到其祖先的儿子,自然要把所有路过的父辈权值加过来。
然后是连接没有关系的节点时,根据数学向量关系推导公式:如图
路径压缩时的图解
#include<bits/stdc++.h>
using namespace std;
const int maxx=1e5+7;
int dis[maxx];
int pre[maxx];
int cot;
void init()
{
for(int i=0;i<maxx;i++)
{
pre[i]=i;
dis[i]=0;
}
cot=0;
}
int find(int x)
{
if(x!=pre[x])
{
int t=pre[x];
pre[x]=find(pre[x]);
dis[x]+=dis[t];
}
return pre[x];
}
void join(int x,int y,int z)
{
int fx=find(x),fy=find(y);
if(fx!=fy)
{
pre[fy]=fx;
dis[fy]=dis[x]+z-dis[y];
}
else{
if(dis[y]-dis[x]!=z) cot++;
}
}
int main()
{
int m,n;
while(~scanf("%d %d",&m,&n))
{
init();
int a,b,c;
for(int i=0;i<n;i++)
{
scanf("%d %d %d",&a,&b,&c);
join(a,b,c);
}
printf("%d\n",cot);
}
}
每次做加权并查集都让我很苦恼,不知道路径压缩以及合并的时候怎么处理数组记录的状态 Zzzzz…图片来源:(https://www.cnblogs.com/newpanderking/archive/2012/10/31/2748567.html))