2020牛客暑期多校训练营(第三场)G题

链接: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");
  }
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值