| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 42639 | Accepted: 13120 |
Description
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
Output
Sample Input
1 5 5 A 1 2 D 1 2 A 1 2 D 2 4 A 1 4
Sample Output
Not sure yet. In different gangs. In the same gang.
Source
带权并查集经典题,第一次做带权并查集的题,relation[ i ]存的是 i 和他父节点的关系,0代表同帮,1异帮,带权并查集需要注意的地方:
1.每次合并的时候,是对两个集合的祖先操作
2.find回溯更新是更新本节点和他父节点的关系
3.注意找好关系,以及表示方式
其余的需要注意的应该就和并查集差不多了。
#include<stdio.h>
int f[100005],relation[100005];
int init(int n)
{
for(int i=0;i<=n;i++)
{
f[i]=i;
relation[i]=0;
}
return 0;
}
int find(int x)
{
if(x==f[x])
return x;
int y=find(f[x]);
relation[x]=(relation[x]+relation[f[x]])%2;
return f[x]=y;
}
int merge(char lc,int a,int b)
{
int t1,t2;
t1=find(a);
t2=find(b);
if(t1==t2)
{
if((relation[a]+relation[b])%2==0)
{
return 1;
}
else
{
return 0;
}
}
if(lc=='D')
{
f[t2]=t1;
relation[t2]=(relation[b]+relation[a]+1)%2;
}
return -1;
}
int main()
{
int t,n,m,a,b;
char ch;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
init(n);
while(m--)
{
getchar();
scanf("%c %d %d",&ch,&a,&b);
if(ch=='D')
{
merge(ch,a,b);
}
else
{
int flog=merge(ch,a,b);
if(flog==-1)
{
printf("Not sure yet.\n");
}
else if(flog==0)
{
printf("In different gangs.\n");
}
else
{
printf("In the same gang.\n");
}
}
}
}
return 0;
}
168




被折叠的 条评论
为什么被折叠?



