並查集 hrbust 1725

Virus Outbreaking
Time Limit: 1000 MS Memory Limit: 32768 K
Total Submit: 120(35 users) Total Accepted: 43(32 users) Rating: Special Judge: No
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
題意:每個人攜帶初始病毒 接觸後攜帶對方病毒 query輸出攜帶病毒
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int pre[10005];
int a[10005];//攜帶病毒 
int n,m;//n個人 m次操作 
int Find(int x)
{
	if(x!=pre[x]) return pre[x] = Find(pre[x]);
	else return x;
} 
void Unit(int x, int y)
{
	int X = Find(x);
	int Y = Find(y);
	if(X!=Y)
		pre[X] = Y;
	return;
}
void Ans(int x)
{
	int count = 0;
	int k[1005];//存放被感染的程序
	for(int i = 1; i <= n; i++)
	{
		if(Find(i)==Find(x))
		{
			int flag = 1;
			for(int j = 0; j < count; j++)
			{
				if(k[j]==a[i])//有相同的不存
				flag = 0; 
			}
			if(flag&&a[i])	k[count++] = a[i];	
		}
	}
	if(count == 0)
		printf("0\n");
	else
	{
		sort(k,k+count);
		for(int i = 0; i < count-1; i++)
			printf("%d ",k[i]);
		printf("%d\n",k[count-1]);
	}
}
int main()
{
	int T;
	while(~scanf("%d",&T))
	{
		while(T--)
		{
			scanf("%d%d",&n,&m);
		pre[0] = 0;
		for(int i = 1; i <= n; i++)
		{
			scanf("%d",&a[i]);
			pre[i] = i;
		}
		while(m--)
		{
			char k[10];
			scanf("%s",k);
			if(strcmp("query",k)==0)
			{
				int h;
				scanf("%d",&h);
				Ans(h);//輸出病毒
			}
			else if(strcmp("touch",k)==0)
			{
				int i,j;
				scanf("%d%d",&i,&j);
				Unit(i,j);//合併節點
			}
		}	
		printf("\n");
	}
	return 0;
 } 
}
 

發佈了46 篇原創文章 · 獲贊 6 · 訪問量 5447
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章