結果

問題 No.416 旅行会社
ユーザー masamasa
提出日時 2016-08-26 23:55:47
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,742 bytes
コンパイル時間 1,192 ms
コンパイル使用メモリ 85,856 KB
実行使用メモリ 24,128 KB
最終ジャッジ日時 2024-04-26 04:05:18
合計ジャッジ時間 12,021 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 -- -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
#include <set>

using namespace std;

typedef pair<int, int> PII;

class UnionFind {
private:
	// parents[i] >= 0 なら i の親
	// parents[i] < 0 で、根。abs(parents[i])がその木に属する頂点数
	vector<int> parents;

public:
	UnionFind();
	UnionFind(int n) {
		parents.assign(n, -1);
	}
	~UnionFind() {
		parents.clear();
	};

	int find(int x) {
		if (parents[x] < 0) {
			return x;
		} else {
			return parents[x] = find(parents[x]);
		}
	}

	void unite(int x, int y) {
		x = find(x);
		y = find(y);

		if (x == y) {
			return;
		}

		if (size(x) < size(y)) {
			swap(x, y);
		}

		parents[x] += parents[y];
		parents[y] = x;
		return ;
	}

	bool same(int x, int y) {
		return find(x) == find(y);
	}

	int size(int x) {
		return -parents[find(x)];
	}
};

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

	cin >> n >> m >> q;
	vector<int> a(m), b(m), c(q), d(q);
	for (int i = 0; i < m; i++) {
		cin >> a[i] >> b[i];
		a[i]--;
		b[i]--;
	}

	set<PII> eaten;
	for (int i = 0; i < q; i++) {
		cin >> c[i] >> d[i];
		c[i]--;
		d[i]--;
		eaten.insert(make_pair(c[i], d[i]));
	}

	UnionFind uf(n);
	for (int i = 0; i < m; i++) {
		if (eaten.count(make_pair(a[i], b[i])) == 0) {
			uf.unite(a[i], b[i]);
		}
	}

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

	int n_connect = uf.size(0);
	for (int i = q - 1; i >= 0; i--) {
		uf.unite(c[i], d[i]);
		if (n_connect == uf.size(0)) {
			continue;
		}

		n_connect = uf.size(0);
		for (int j = 0; j < n; j++) {
			if (ans[j] == 0 && uf.same(0, j)) {
				ans[j] = i + 1;
			}
		}
	}

	for (int i = 1; i < n; i++) {
		cout << ans[i] << endl;
	}
	return 0;
}
0