solution

頂点に付加情報を乗せたunion-find木。$O(N + M \alpha(N))$。

implementation

#include <cstdio>
#include <map>
#include <vector>
#define repeat(i, n) for (int i = 0; (i) < int(n); ++(i))
using namespace std;

struct disjoint_sets {
    vector<int> data;
    disjoint_sets() = default;
    explicit disjoint_sets(size_t n) : data(n, -1) {}
    bool is_root(int i) { return data[i] < 0; }
    int find_root(int i) { return is_root(i) ? i : (data[i] = find_root(data[i])); }
    int set_size(int i) { return - data[find_root(i)]; }
    int unite_sets(int i, int j) {
        i = find_root(i); j = find_root(j);
        if (i != j) {
            if (set_size(i) < set_size(j)) swap(i,j);
            data[i] += data[j];
            data[j] = i;
        }
        return i;
    }
    bool is_same(int i, int j) { return find_root(i) == find_root(j); }
};

int main() {
    int n, m; scanf("%d%d", &n, &m);
    disjoint_sets ds(n);
    map<int, int> boss;
    repeat (i, n) {
        boss[i] = i;
    }
    repeat (i, m) {
        int a, b; scanf("%d%d", &a, &b); -- a; -- b;
        int root_a = ds.find_root(a);
        int root_b = ds.find_root(b);
        if (root_a == root_b) continue;
        int next_boss = make_pair(ds.set_size(a), - boss[root_a]) < make_pair(ds.set_size(b), - boss[root_b]) ? boss[root_b] : boss[root_a];
        ds.unite_sets(a, b);
        boss.erase(root_a);
        boss.erase(root_b);
        boss[ds.find_root(a)] = next_boss;
    }
    repeat (i, n) {
        printf("%d\n", boss[ds.find_root(i)] + 1);
    }
    return 0;
}