链接:https://ac.nowcoder.com/acm/contest/5668/G
来源:牛客网
示例一:
输入:
5
4 3
0 1
1 2
2 3
4
0 1 3 0
4 3
0 1
1 2
2 3
2
0 2
4 3
0 1
1 2
2 3
2
0 3
4 1
1 3
1
2
5 5
0 1
0 2
1 2
1 3
3 4
3
4 4 0
输出:
0 0 0 0
2 2 2 2
0 0 3 3
0 1 2 3
0 0 0 0 0
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <list>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 8e5 + 20;
int fa[maxn];
vector<int> graph[maxn];
list<int> lis[maxn];
bool v[maxn];
int n, m, q;
int x, y, xx, yy;
int get(int x)
{
if (x == fa[x])
return x;
return fa[x] = get(fa[x]);
}
void merge(int x, int y)
{
fa[get(x)] = get(y);
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++)
{
lis[i].clear();
lis[i].push_back(i);
fa[i] = i;
graph[i].clear();
v[i] = 0;
}
for (int i = 0; i < m; i++)
{
scanf("%d%d", &x, &y);
graph[y].push_back(x);
graph[x].push_back(y);
}
scanf("%d", &q);
while (q--)
{
scanf("%d", &x);
if (x != (xx = get(x)))
continue;
int siz = lis[x].size();
while (siz--)
{
int iter = lis[x].front();
for (int i = 0; i < graph[iter].size(); i++)
{
y = graph[iter][i];
yy = get(y);
if (xx != yy)
{
fa[yy] = xx;
lis[x].splice(lis[x].end(), lis[yy]);
}
}
lis[x].pop_front();
}
}
for (int i = 0; i < n; i++)
{
printf("%d", get(i));
if (i < n - 1)
printf(" ");
else
printf("\n");
}
}
}