题意
给出一张图,上面的边都有蓝或红这两种颜色。选择一个点可以使得它连出的所有边的颜色变反,求选择的最少点数使得图的边只有一种颜色,如果不能满足只有一种颜色,输出-1。
思路
当我们选择一个点时,我们可以确定它连到的点需不需要选择,因为要保证边的颜色,所以我们可以默认一个颜色,然后搜索判断记录最少选择的点。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
const int inf = 2147483647 / 3;
int n, m, tot, mins, sum, flag;
int ver[200001], next[200001], edge[200001], head[200001], v[100001], f[100001], run[100001];
void add(int x, int y, char w) {
ver[++tot] = y;
next[tot] = head[x];
head[x] = tot;
edge[tot] = (w == 'R');
}
void dfs(int x) {
v[x] = run[x] = 1;
for (int i = head[x]; i; i = next[i]) {
if (flag) break;
int y = ver[i];
if (!v[y]) {
f[y] = f[x] ^ edge[i];//确保边为0
if (f[y]) sum++;
dfs(y);
}
else if(f[y] != f[x] ^ edge[i])//不能满足颜色一致
flag = 1;
}
}
void solve() {
memset(run, 0, sizeof(run));
int ans = 0, k;
for (int i = 1; i <= n; i++) {
if (run[i]) continue;
f[i] = sum = flag = 0;
memset(v, 0, sizeof(v));
dfs(i);
if (flag) k = inf;
else k = sum;
f[i] = sum = 1;
flag = 0;
memset(v, 0, sizeof(v));
dfs(i);
if (flag) sum = inf;
if (k == inf && sum == inf) {
ans = inf;
break;
}
ans += std::min(k, sum);//加上每个连通块的答案
}
mins = std::min(ans, mins);
}
int main() {
scanf("%d %d",&n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
char c;
scanf("%d %d %c", &x, &y, &c);
add(x, y, c);
add(y, x, c);
}
mins = inf;
solve();
for (int i = 1; i <= tot; i++)
edge[i] ^= 1;
solve();
if (mins == inf) printf("-1");
else printf("%d", mins);
}