Problem C C 、 小 花梨 判连通
时间限制:2000ms 空间限制:512MB
Description
小花梨给出𝑜个点,让𝑙位同学对这𝑜个点任意添加无向边,构成𝑙张图。小花梨想知道对于
每个点𝑗,存在多少个点𝑘(包括𝑗本身),使得𝑗和𝑘在这𝑙张图中都是连通的。
Input
第一行输入两个正整数𝑜和𝑙,分别表示点的个数和同学数。
接下来分成𝑙部分进行输入,每部分输入格式相同。
每部分第一行输入一个整数𝑏𝑗,表示第𝑗位同学连边的数目。
接下来𝑏𝑗行,每行两个正整数𝑣,𝑤,表示第𝑗位同学将点𝑣和点𝑤之间进行连接。
可能会存在重边或者自环。
(1 ≤ 𝑜 ≤ 100000,1 ≤ 𝑙 ≤ 10,1 ≤ 𝑣,𝑤 ≤ 𝑜,0 ≤ 𝑏𝑗 ≤ 200000)
Output
输出𝑜行,第𝑗行输出在𝑙张图中都和编号为𝑗的点连通的点的数目(包括𝑗本身)
Example
Sample Input Sample Output
4 2
3
1 2
1 3
2 3
2
1 2
3 4
2
2
1
1
思路:
· 我们如果根据图中每一条边进行并查集的merge,那么在一张图中,如果两个节点联通,那么他们的祖先一定相等。
那么我们对每一个节点创建一个vector,来依次存它在k张图中的祖先。
那么我们可以知道 如果两个节点在k张图中都联通,那么它们的vector数组是相等的。
然后我们不妨使用map对vector 出现的次数进行统计,从而可以得出答案。
细节见代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define chu(x) cout<<"["<<#x<<" "<<(x)<<"]"<<endl
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) {ll ans = 1; while (b) {if (b % 2) { ans = ans * a % MOD; } a = a * a % MOD; b /= 2;} return ans;}
inline void getInt(int *p);
const int maxn = 100010;
const int inf = 0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int far[maxn];
int n;
void init()
{
repd(i, 1, n) {
far[i] = i;
}
}
int findpar(int x)
{
if (x == far[x]) {
return x;
} else {
return far[x] = findpar(far[x]);
}
}
void merge_(int x, int y)
{
x = findpar(x);
y = findpar(y);
if (x != y) {
far[x] = y;
}
}
int k;
std::vector<int> v[maxn];
map<vector<int>, int> vis;
int main()
{
//freopen("D:\\code\\text\\input.txt","r",stdin);
//freopen("D:\\code\\text\\output.txt","w",stdout);
gbtb;
cin >> n >> k;
int num;
while (k--) {
init();
cin >> num;
repd(i, 1, num) {
int x, y;
cin >> x >> y;
merge_(x, y);
}
repd(i, 1, n) {
v[i].push_back(findpar(i));
}
}
// repd(i, 1, n) {
// for (auto x : v[i]) {
// cout << x << " ";
// }
// cout << endl;
// }
repd(i, 1, n) {
vis[v[i]]++;
}
repd(i, 1, n) {
cout << vis[v[i]] << endl;
}
return 0;
}
inline void getInt(int *p)
{
char ch;
do {
ch = getchar();
} while (ch == ' ' || ch == '\n');
if (ch == '-') {
*p = -(getchar() - '0');
while ((ch = getchar()) >= '0' && ch <= '9') {
*p = *p * 10 - ch + '0';
}
} else {
*p = ch - '0';
while ((ch = getchar()) >= '0' && ch <= '9') {
*p = *p * 10 + ch - '0';
}
}
}