Firetrucks Are Red

链接 : https://codeforces.com/gym/102500/problem/F

题意 :

给定 n 组, 每组 m 个数, 如果两个组有共同数, 则这两个组相关. 问是否每个组两两之间都相关. 若是, 打印 n - 1条边, 使得所有组相关.

思路 :

记录每个数有哪些组, 然后并查集合并即可.

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 2e5 + 10;
int p[N];

int find(int x) {
    return p[x] == x ? x : p[x] = find(p[x]);
}

bool add(int x, int y) {
    int fx = find(x), fy = find(y);
    if (fx != fy) {
        p[fx] = fy;
        return true;
    }
    return false;
}

struct node {
    int a, b, c;
};

int main() {	
    int n, m, x;
    unordered_map<int, vector<int>> mp;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        p[i] = i;
        scanf("%d", &m);
        while (m--) {
            scanf("%d", &x);
            mp[x].pb(i);
        }
    }
    vector<node> ans; 
    for (auto t : mp) 
        for (int i = 1; i < t.se.size(); ++i) 
            if (add(t.se[i], t.se[i - 1])) 
                ans.pb({t.se[i], t.se[i - 1], t.fi});
    
    if (ans.size() != n - 1) 
        printf("impossible\n");
    else 
        for (auto t : ans) printf("%d %d %d\n", t.a, t.b, t.c);
    return 0;
}
posted @ 2020-11-22 19:55  phr2000  阅读(107)  评论(0编辑  收藏  举报