题解:AT_agc064_b [AGC064B] Red and Blue Spanning Tree
题意
给定一个无向连通图,每个点是红色或蓝色的,每条边也是红色或蓝色的。每种颜色的点都得有一条相应颜色的边连向它,要求在这种限制下构造出一棵生成树。
思路
把边分
- 第
1 类:这条边的颜色和这条边两个端点的颜色都相同。 - 第
2 类:这条边的颜色和这条边其中一个端点的颜色相同。 - 第
3 类:这条边的颜色和这条边两个端点的颜色都不相同。
首先,我们把第
其次,我们来选第
具体实现:我们用一个队列来记录已经满足条件了的点,每次把队首的点出队,枚举它连出去的
证明:如果我们选了一条
最后,我们把所有之前没选的边都尽可能地选以保证连通性。当然,不能构成环。
时间复杂度
因为用到并查集,所以时间复杂度要带
时间复杂度:
代码实现
AC link
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define unll unsigned long long
#define bint __int128
#define set_q priority_queue
#define unmp unordered_map
mt19937_64 mrand((unll) std::chrono::steady_clock::now().time_since_epoch().count());
inline ll in () {
ll x = 0; bool f = false; char ch = getchar();
while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return f ? -x : x;
}
const ll p = 1000000007, inf = 1ll << 60ll, infless = -(1ll << 60ll);
inline ll quickpow (const ll &a, const ll &n) {
ll res = 1ll, t = a;
for (ll y = n; y > 0; y >>= 1) {
if (y & 1) {
res *= t;
res %= p;
}
t *= t;
t %= p;
}
return res;
}
const int N = 200100, M = 520;
int test, n, m, a[N], len1, len2, fa[N];
char s[N], t[M];
bool b[N];
vector<array<int, 2> > edges[N];
vector<int> e;
array<int, 4> edges1[N], edges2[N], edge[N];
ll ans = 0ll;
inline int findset (int x) {
return x == fa[x] ? x : fa[x] = findset(fa[x]);
}
inline void bfs () {
queue<int> q;
for (int i = 1; i <= n; i++) {
if (b[i]) {
q.push(i);
}
}
while (!q.empty()) {
auto x = q.front();
q.pop();
for (auto [y, id] : edges[x]) {
int fx = findset(x), fy = findset(y);
if (fx != fy) {
fa[fy] = fx;
if (!b[y]) {
b[y] = true;
q.push(y);
}
e.push_back(id);
}
}
}
}
inline void solve () {
ans = 0ll;
//solve clear !
n = in(), m = in();
for (int i = 1; i <= m; i++) {
int x = in(), y = in();
scanf("%s", t + 1);
int ty = 0;
if (t[1] == 'B') {
ty = 1;
}
edge[i] = {x, y, ty, i};
}
scanf("%s", s + 1);
for (int i = 1; i <= n; i++) {
a[i] = s[i] == 'B' ? 1 : 0;
}
for (int i = 1; i <= m; i++) {
auto [x, y, ty, id] = edge[i];
if (ty == a[x] && ty == a[y]) {
edges1[++len1] = edge[i];
} else {
if (ty != a[x] && ty != a[y]) {
edges2[++len2] = edge[i];
} else {
if (ty == a[x]) {
edges[y].push_back({x, id});
} else {
edges[x].push_back({y, id});
}
}
}
}
for (int i = 1; i <= n; i++) {
fa[i] = i;
}
for (int i = 1; i <= len1; i++) {
auto [x, y, ty, id] = edges1[i];
int fx = findset(x), fy = findset(y);
if (fx != fy) {
fa[fx] = fy;
b[x] = b[y] = true;
e.push_back(id);
}
}
bfs();
for (int i = 1; i <= m; i++) {
auto [x, y, ty, id] = edge[i];
int fx = findset(x), fy = findset(y);
if (fx != fy) {
e.push_back(id);
fa[fx] = fy;
}
}
for (int i = 1; i <= n; i++) {
int fx = findset(i);
if (!b[i] || fx != findset(1)) {
puts("No");
return;
}
}
sort(e.begin(), e.end());
e.erase(unique(e.begin(), e.end()), e.end());
puts("Yes");
for (auto x : e) {
printf("%d ", x);
}
puts("");
return;
}
int main() {
for (test = 1; test--; solve());
return 0;
}