[Improve JZOJ 4672. A set of simulated race T2] Graph Coloring

Subject to the effect:

You now have a non-directed graph comprising n nodes and m edges. Initially, each side is blue or red. Each time you can color all the edges connected to a node (from red to blue, red and blue).
A minimum number of steps to find the program, so that all sides of the same color. If no program outputs -1

Problem-solving ideas:

It can be set as object search and blue, if the current click once it shows no program
is then inverted right side all (the object changed to red) in the same manner

A c c e p t e d / c O d e : Accepted/ code:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 110000;
const int inf = 2147483647 / 3;

struct Line {
	int to, w, next;
}e[N<<1];

int n, m, cnt, sum, ans;
int last[N];
bool flag;
bool v[N], f[N], a[N];

inline void add(int x, int y, int w) {
	e[++cnt] = (Line){y, w, last[x]}; last[x] = cnt;
}

void dfs(int x) {
	v[x] = a[x] = 1;
	for (int i = last[x]; i && !flag; i = e[i].next) {
		int y = e[i].to;
		if (!v[y]) {
			f[y] = f[x] ^ e[i].w;
			if (f[y]) sum++;
			dfs(y);
		}
		else if(f[y] != f[x] ^ e[i].w)
			     flag = 1;
	}
}

void count() {
	memset(a, 0, sizeof(a));
	int answer = 0, k;
	for (int i = 1; i <= n; i++)
		if (!a[i]) {
		  	f[i] = sum = flag = 0;
		  	memset(v, 0, sizeof(v));
		  	dfs(i);
		  	if (flag) k = inf;
		  	else k = sum;
		  	k = flag ? inf : sum;
		  	f[i] = sum = 1; flag = 0;
		  	memset(v, 0, sizeof(v));
		  	dfs(i);
		  	if (flag) sum = inf;
		  	if (k == inf && sum == inf) {
		  		answer = inf;
		  		break;
		  	}
			answer += min(k, sum);
		}
	ans = min(answer, ans);
}

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 1, x, y; i <= m; ++i) {
		char c;
		scanf("%d %d %c", &x, &y, &c);
		add(x, y, c == 'B');
		add(y, x, c == 'B');
	}
	ans = inf;
	count();
	for (int i = 1; i <= cnt; ++i)
		e[i].w ^= 1;
	count();
	printf("%d", ans == inf ? -1 : ans);
}

Guess you like

Origin blog.csdn.net/qq_39798042/article/details/88900160