The police office in Tadu City decides to say ends to the chaos, as launch actions to root up the TWO gangs in the city, Gang Dragon and Gang Snake. However, the police first needs to identify which gang a criminal belongs to. The present question is, given two criminals; do they belong to a same clan? You must give your judgment based on incomplete information. (Since the gangsters are always acting secretly.)
Assume N (N <= 10^5) criminals are currently in Tadu City, numbered from 1 to N. And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. You will be given M (M <= 10^5) messages in sequence, which are in the following two kinds:
1. D [a] [b]
where [a] and [b] are the numbers of two criminals, and they belong to different gangs.
2. A [a] [b]
where [a] and [b] are the numbers of two criminals. This requires you to decide whether a and b belong to a same gang.Input
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. Each test case begins with a line with two integers N and M, followed by M lines each containing one message as described above.
Output
For each message "A [a] [b]" in each case, your program should give the judgment based on the information got before. The answers might be one of "In the same gang.", "In different gangs." and "Not sure yet."
Sample Input
1 5 5 A 1 2 D 1 2 A 1 2 D 2 4 A 1 4Sample Output
Not sure yet. In different gangs. In the same gang.题目大意:
输入n和m,代表有n个人和m个询问,每个询问遵循下面的规则:
- A a b要求输出a与b是否在同一个帮派或者不能确定。
- D a b告诉你a和b是不同帮派的成员。
思路与分析:并查集就加上了权值了,权值代表的是与父亲节点的关系,说明父亲节点改变的话,该节点的权值也会发生相应的变化,这时候就要两个方面:路径压缩和合并,因为两者都有父亲节点的变化,说明权值要发生相应的变化。这些变化可以用向量的加减来表示,用root存储每个节点的根节点,用re表示从该节点出发的向量权值,比如:
1.压缩的时候:
比如将C节点连到A的时候,那么就会有条从C到A的向量,那么C到A这条向量的权值就是1+0=1,所以说明B和A是同伙,B和C是敌人,那么则推出A和C是敌人,对应的代码就是re[a]=(re[a]+re[root[a]])%2,%2是为了保证当相加超过2时的情况,这样取出来的结果能保证是0或者1。
2.合并的时候:
当知道A和B是敌人,则A和B之间有条权值为1的边,C和D分别是A和B的根节点,所以要把合并C到D,那么C到D之间的权值就是-re[A]+1+re[B]了;如果是把D合到C则公式是re[A]-1-re[B]了。同时,如果同样为了保证只取到0和1两个值,可以进行+2在%2处理。所以公式为(-re[A]+1+re[B]+2)%2或者(re[A]-1-re[B]+2)%2。这样的话,也可以知道c和d之间的关系了。3.查询:
当知道两个元素处于同一根节点之后判断是同伙还是敌人,则公式为(re[D]-re[C]+2)%2。如果值为0,说明为同伙,如果是1,说明为敌人。
代码如下:
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; int p[100005]; int r[100005]; int Find(int a) { if(a == p[a]) return a; int t = p[a]; p[a] = Find(p[a]); r[a] = (r[a]+r[t])%2; return p[a]; } void Union(int a, int b) { int A = Find(a); int B = Find(b); p[A] = B; r[A] = (r[a]+1+r[b])%2; } int main() { int T; int N,M; cin>>T; while(T--) { cin>>N>>M; for(int i=1 ; i<=N ; i++) { p[i] = i; r[i] = 0; } while(M--) { char ch; int a,b; getchar(); scanf("%c %d %d",&ch,&a,&b); if(ch == 'A') { if(Find(a) != Find(b)) cout<<"Not sure yet."<<endl; else { if(r[a] != r[b]) cout<<"In different gangs."<<endl; else cout<<"In the same gang."<<endl; } } else if(ch == 'D') Union(a,b); } } return 0; }
Find them, Catch them POJ - 1703 (带权并查集)
最新推荐文章于 2020-07-22 18:52:28 发布