結果
| 問題 |
No.416 旅行会社
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2017-11-03 18:50:18 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 443 ms / 4,000 ms |
| コード長 | 2,682 bytes |
| コンパイル時間 | 2,524 ms |
| コンパイル使用メモリ | 187,316 KB |
| 実行使用メモリ | 15,068 KB |
| 最終ジャッジ日時 | 2024-12-14 20:26:33 |
| 合計ジャッジ時間 | 7,722 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 21 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
struct Union_Find {
//各要素が属する集合の代表(根)を管理する
//もし、要素xが根であればdata[x]は負の値を取り、-data[x]はxが属する集合の大きさに等しい
vector<int> data;
Union_Find(int size) : data(size, -1) {}
bool Union(int x, int y) {
x = Find(x);
y = Find(y);
bool is_union = (x != y);
if (is_union) {
if (data[x] > data[y]) swap(x, y);
data[x] += data[y];
data[y] = x;
}
return is_union;
}
int Find(int x) {
if (data[x] < 0) { //要素xが根である
return x;
} else {
data[x] = Find(data[x]); //data[x]がxの属する集合の根でない場合、根になるよう更新される
return data[x];
}
}
bool same(int x, int y) {
return Find(x) == Find(y);
}
int size(int x) {
return -data[Find(x)];
}
};
void mergeTech(int x, int y, vector< vector<int> >& vv) {
if (x == y) return;
if (vv[x].size() < vv[y].size()) swap(x, y);
for (int hoge : vv[y]) vv[x].push_back(hoge);
vv[y].clear();
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n, m, q;
cin >> n >> m >> q;
set<P> sp;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
sp.emplace(a, b);
}
vector<P> vp;
for (int i = 0; i < q; i++) {
int c, d;
cin >> c >> d;
c--;
d--;
vp.emplace_back(c, d);
sp.erase(vp.back());
}
Union_Find uf(n);
vector< vector<int> > vv(n);
for (int i = 0; i < n; i++) vv[i].push_back(i);
for (auto& p : sp) {
mergeTech(uf.Find(p.first), uf.Find(p.second), vv);
uf.Union(p.first, p.second);
}
vector<int> ans(n, 0);
for (int i = 0; i < n; i++) {
if (uf.same(0, i)) ans[i] = -1;
}
for (int i = q - 1; i >= 0; i--) {
if (!uf.same(0, vp[i].first) && uf.same(0, vp[i].second)) {
for (int x : vv[uf.Find(vp[i].first)]) {
if (ans[x] == 0) ans[x] = i + 1;
}
}
if (!uf.same(0, vp[i].second) && uf.same(0, vp[i].first)) {
for (int x : vv[uf.Find(vp[i].second)]) {
if (ans[x] == 0) ans[x] = i + 1;
}
}
mergeTech(uf.Find(vp[i].first), uf.Find(vp[i].second), vv);
uf.Union(vp[i].first, vp[i].second);
}
for (int i = 1; i < n; i++) {
cout << ans[i] << endl;
}
return 0;
}