結果
| 問題 |
No.1640 簡単な色塗り
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-08-06 23:35:56 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 261 ms / 2,000 ms |
| コード長 | 2,599 bytes |
| コンパイル時間 | 3,143 ms |
| コンパイル使用メモリ | 213,100 KB |
| 最終ジャッジ日時 | 2025-01-23 16:16:35 |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 53 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
struct UnionFind{
vector<int> par;
vector<int> rank;
vector<int> cnt;
UnionFind(int n){
par.resize(n);
rank.resize(n);
cnt.resize(n, 0);
for(int i = 0; i < n; i++){
par[i] = i;
rank[i] = 1;
}
}
int root(int x){
if(par[x] == x) return x;
else return par[x] = root(par[x]);
}
bool same(int x, int y){
return root(x) == root(y);
}
bool unite(int x, int y){
x = root(x);
y = root(y);
if(x == y) {
cnt[x] += 1;
return false;
}
if(rank[x] < rank[y]) swap(x, y);
par[y] = x;
rank[x] += rank[y];
cnt[x] += cnt[y] + 1;
return true;
}
int size(int x) {
return rank[root(x)];
}
int count(int x){
return cnt[root(x)];
}
};
int main(){
int N;
cin >> N;
vector<int> A(N), B(N);
UnionFind U(N);
vector<vector<pair<int, int>>> G(N);
vector<int> r, le, ri, ind;
for(int i = 0; i < N; i++) {
cin >> A[i] >> B[i];
A[i]--;
B[i]--;
bool f = U.unite(A[i], B[i]);
if(!f) {
r.push_back(A[i]);
le.push_back(A[i]);
ri.push_back(B[i]);
ind.push_back(i);
}
else{
G[A[i]].push_back({B[i], i});
G[B[i]].push_back({A[i], i});
}
}
vector<bool> used(N, false);
bool f = true;
for(int i = 0; i < N; i++){
int t = U.root(i);
if(used[t]) continue;
used[t] = true;
if(U.size(i) != U.count(i)) f = false;
}
if(!f) cout << "No" << endl;
else{
cout << "Yes" << endl;
vector<int> ans(N);
for(int i = 0; i < N; i++) ans[i] = i;
used.assign(N, false);
auto dfs = [&](auto dfs, int now, int par) -> void{
for(auto [to, id] : G[now]){
if(to == par) continue;
ans[id] = to;
used[to] = true;
dfs(dfs, to, now);
}
};
for(int i = 0; i < (int)r.size(); i++){
dfs(dfs, r[i], -1);
}
for(int i = 0; i < (int)le.size(); i++){
if(!used[le[i]]) {
ans[ind[i]] = le[i];
used[le[i]] = true;
}
else if(!used[ri[i]]) {
ans[ind[i]] = ri[i];
used[ri[i]] = true;
}
}
for(int i = 0; i < N; i++) cout << ans[i] + 1 << endl;
}
}