不确定思路错还是代码错 思路:如果数据有解就先构造生成树,然后随便找一个不在树上的边,如果边上两点是祖先后代关系就将祖先以下(不含)染成黑色,其余全部染成白色,如果不是祖先后代关系就将二者的子树(含)都染成黑色,其余全部白色 代码:
#include <iostream>
#include <vector>
// #ifndef ONLINE_JUDGE
// #define ONLINE_JUDGE
// #endif
#ifdef ONLINE_JUDGE
#define TEST
#endif
#ifndef TEST
#define DEBUG
#endif
typedef long long ll;
using namespace std;
#ifdef DEBUG
constexpr bool debug = true;
#else
constexpr bool debug = false;
#endif
constexpr int maxn = 200010;
class UnionSets {
private:
int fa[maxn];
public:
void init(const int n) {
for (int i = 1; i <= n; ++i)
fa[i] = i;
}
int find(const int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void merge(const int x, const int y) {
fa[find(x)] = find(y);
}
}sts;
int colors[maxn];
vector<int> V[maxn];
void dfs(const int x, const int fa, bool color, const int exu, const int exv) {
if (x == exu || x == exv) {
if (color)
colors[exu ^ exv ^ x] = false;
color = true;
}
colors[x] = color;
for (int v : V[x]) {
if (v == fa)
continue;
dfs(v, x, color, exu, exv);
}
}
int main() {
#ifdef TEST
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
#endif
// type in your program here
int T, n, m;
cin >> T;
while (T--) {
bool extra;
int u, v, exu, exv;
cin >> n >> m;
sts.init(n);
for (int i = 1; i <= n; ++i)
V[i].clear();
extra = false;
while (m--) {
cin >> u >> v;
if (sts.find(u) == sts.find(v))
extra = true, exu = u, exv = v;
else {
sts.merge(u, v);
V[u].push_back(v);
V[v].push_back(u);
}
}
if (n <= 2) {
cout << "-1\n";
continue;
}
bool impossible = false;
for (int i = 2; i <= n; ++i)
if (sts.find(i) != sts.find(1))
impossible = true;
if (impossible || !extra) {
cout << "-1\n";
continue;
}
const bool hv1 = (exu == 1 || exv == 1);
const bool hv2 = (exu == 2 || exv == 2);
if (!hv1) dfs(1, 0, 0, exu, exv);
else if (!hv2) dfs(2, 0, 0, exu, exv);
else dfs(3, 0, 0, exu, exv);
for (int i = 1; i <= n; ++i)
cout << (colors[i] ? 'B' : 'W');
cout << '\n';
}
#ifndef TEST
while (true);
#endif
return 0;
}