結果

問題 No.416 旅行会社
ユーザー pekempeypekempey
提出日時 2016-08-26 22:43:31
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 339 ms / 4,000 ms
コード長 1,440 bytes
コンパイル時間 2,102 ms
コンパイル使用メモリ 159,732 KB
実行使用メモリ 14,784 KB
最終ジャッジ日時 2023-08-21 09:36:44
合計ジャッジ時間 5,925 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 92 ms
10,908 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 4 ms
4,380 KB
testcase_09 AC 13 ms
4,488 KB
testcase_10 AC 109 ms
10,976 KB
testcase_11 AC 107 ms
11,100 KB
testcase_12 AC 112 ms
11,096 KB
testcase_13 AC 89 ms
10,780 KB
testcase_14 AC 339 ms
13,932 KB
testcase_15 AC 337 ms
13,992 KB
testcase_16 AC 336 ms
14,176 KB
testcase_17 AC 339 ms
13,876 KB
testcase_18 AC 334 ms
14,004 KB
testcase_19 AC 227 ms
14,640 KB
testcase_20 AC 224 ms
14,784 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

struct UnionFind {
	vector<int> parent;
	vector<vector<int>> group;

	UnionFind(int n) : parent(n), group(n) {
		for (int i = 0; i < n; i++) {
			parent[i] = i;
			group[i].push_back(i);
		}
	}

	int operator[](int x) {
		if (parent[x] == x) return x;
		return parent[x] = operator[](parent[x]);
	}

	bool merge(int x, int y) {
		x = operator[](x);
		y = operator[](y);
		if (x == y) return false;
		if (x > y) swap(x, y);
		if (group[x].size() < group[y].size()) swap(group[x], group[y]);
		for (int e : group[y]) group[x].push_back(e);
		parent[y] = x;
		return true;
	}
};

int main() {
	int n, m, q;
	cin >> n >> m >> q;

	set<pair<int, int>> g;

	for (int i = 0; i < m; i++) {
		int a, b;
		scanf("%d %d", &a, &b);
		a--; b--;
		g.emplace(minmax(a, b));
	}

	vector<int> c(q), d(q);
	for (int i = 0; i < q; i++) {
		scanf("%d %d", &c[i], &d[i]);
		c[i]--; d[i]--;
		g.erase(minmax(c[i], d[i]));
	}

	UnionFind uf(n);
	for (auto e : g) {
		uf.merge(e.first, e.second);
	}

	vector<int> ans(n);

	for (int i = 0; i < n; i++) {
		if (uf[0] == uf[i]) {
			ans[i] = -1;
		}
	}

	for (int i = q - 1; i >= 0; i--) {
		c[i] = uf[c[i]];
		d[i] = uf[d[i]];
		if (c[i] > d[i]) swap(c[i], d[i]);
		if (c[i] != d[i]) {
			if (c[i] == 0) {
				for (int e : uf.group[d[i]]) {
					ans[e] = i + 1;
				}
			}
			uf.merge(c[i], d[i]);
		}
	}

	for (int i = 1; i < n; i++) {
		printf("%d\n", ans[i]);
	}
}
0