Virus Outbreaking | ||||||
| ||||||
Description | ||||||
Village H is suffering a virus outbreaking. There are n persons in the village, some of them is infected by at most one virus.
| ||||||
Input | ||||||
There are multiple test cases. The first line is an integer T indicating the number of test cases. The first line of each case is two positive integers n and q. n is the number of persons in the village and q is the times of event happened in village H. The second line of each case is n numbers a1, a2, ..., an separated by space. ai stands for the kind of virus the ith person infected. 0 means not infected. Then q lines following, each is an event happened in the village, consist of touching or query ordered by happening: touch A B: a touched b and they infected each other. They will be together until the end. query A: ask how many kind of virus person A infected. If A is not infected, output 0. There will be a blank line after each case.
Note: 1 <= n <= 1000, 1 <= q <= 1000, 0 <= ai <= 32.
| ||||||
Output | ||||||
For each query, output one line consist of all kinds of virus the person A infected, Output them by the increasing order, separated by space. Output a blank line after each test case. | ||||||
Sample Input | ||||||
2 4 6 20 14 24 30 query 1 query 4 query 4 query 4 touch 1 4 query 2 4 6 7 4 28 20 touch 4 1 query 2 query 1 query 3 query 3 query 1 | ||||||
Sample Output | ||||||
20 30 30 30 14 4 7 20 28 28 7 20 | ||||||
Hint | ||||||
Source | ||||||
哈理工2013春季校赛 - 网络预选赛 | ||||||
Author | ||||||
黄李龙@HRBUST |
写完这最后一篇题解,就准备收拾收拾东西上火车了,寒假的最后一发、做的还算开心。
一道并查集的题目,英语好的,读懂题意马上就能AC;
题目大意:【自己看输出猜的】有n个人,m个提问,n个数代表n个人的权值,touch操作表示连接两个人,query表示查询这个人所在集合所有人的权值。【从小到大,并且不要重复】、
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[1024];
int f[1024];
int n,m;
int find(int x)
{
return f[x] == x ? x : (f[x] = find(f[x]));
}
void merge(int a,int b)
{
int A,B;
A=find(a);
B=find(b);
if(A!=B)
f[B]=A;
}
int findans(int b)
{
int ans[1024];
int cont=0;
for(int i=1;i<=n;i++)
{
if(find(i)==find(b))
{
int ok=1;
for(int j=0;j<cont;j++)
{
if(ans[j]==a[i])
{
ok=0;
}
}
if(ok&&a[i])
{
ans[cont]=a[i];
cont++;
}
}
}
if(cont==0)
{
printf("0\n");
}
else
{
sort(ans,ans+cont);
for(int i=0;i<cont-1;i++)
{
printf("%d ",ans[i]);
}
printf("%d\n",ans[cont-1]);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
f[i]=i;
}
while(m--)
{
char str[50];
scanf("%s",str);
if(str[0]=='t')
{
int x,y;
scanf("%d%d",&x,&y);
merge(x,y);
}
if(str[0]=='q')
{
int x;
scanf("%d",&x);
findans(x);
}
}
printf("\n");
}
}