Find them, Catch them?点击打开题目链接
Description 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.) 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 Sample Output
|
楼主在做这个提的时候花了很长时间,因为一直没搞明白如何压缩路径,然后每次就是TLE,搞得我很迷茫,好不容易压缩路的部分没问题了,又在更新结点与根的关系的步骤上除了维妮塔,出现了逻辑维妮塔,因为要更新这个点与祖先节点的关系,就要更新这个点与父节点之间的关系,那么首先更新父节点与祖先节点之间的关系......逐次往上,最终更新了这个点与祖先节点之间的关系。就是下面这个代码:
int search(int x)
{
if(pre[x]==x)
return x;
int t=pre[x];
//rel[x]=(rel[x]+rel[t])%2;
pre[x]=search(pre[x]);
rel[x]=(rel[x]+rel[t])%2;
return pre[x];
}
注释掉的那句是我WA那下iefa,我是先更新他与他父节点的关系,在压缩路径,这样最终这个点存的是这个点与他父节点的关系,而不是和他祖先节点的关系!
下面是完整代码:
#include<iostream>
#include<cstdio>
using namespace std;
int pre[100010];
int rel[100010];
long long k,ansa,ansb;
int search(int x)
{
if(pre[x]==x)
return x;
int t=pre[x];
//rel[x]=(rel[x]+rel[t])%2;
pre[x]=search(pre[x]);
rel[x]=(rel[x]+rel[t])%2;
return pre[x];
}
int Merge(int x,int y)
{
int fx=search(x);
int fy=search(y);
pre[fx]=fy;
rel[fx]=(rel[x]+1+rel[y])%2;
}
int main()
{
char ch[2];
int n,m,a,b,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
pre[i]=i;
rel[i]=0;
}
for(int i=1;i<=m;i++)
{
scanf("%s%d%d",ch,&a,&b);
if(ch[0]=='D')
Merge(a,b);
else
{
if(search(a)==search(b))
{
if(rel[a]!=rel[b])
cout<<"In different gangs."<<endl;
else
cout<<"In the same gang."<<endl;
}
else
cout<<"Not sure yet."<<endl;
}
}
}
return 0;
}