Test instructions: There is a non-direction graph and three colors, the number of vertices n<=500, the set of all vertices that can be reached from a vertex u is the S (U), the points in S (U) can reach each other and only through the points in S (U), which specifies that the two endpoints of an edge cannot dye the same color. Ask if there is a viable solution.
Idea: If the time complexity of direct violence is 3^n, obviously can't bear.
Considering any one node u, then the sub-graph of all the points in S (U) is unicom and the points in S (U) can only dye the other two colors, because the graph is connected, so the dyeing scheme is definitely unique, that is, we have a two-point graph for each node dyeing, if there is a conflict then there is no scheme. The time complexity is reduced to O (n*n).
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream > #include <algorithm> #include <vector> #include <map> #include <queue> #include <stack > #include <string> #include <map> #include <set> #include <ctime> #define EPS 1e-6#define LL Long Long#define PII (Pair<int, int>)//#pragma comment (linker, "/stack:1024000000,1024000000") using namespace std;const int MAXN = 600;const int INF = 500000;vector<int> G[maxn];char mayor[10] = {0, ' R ', ' G ', ' B '};int N, m;int Color[maxn];queue<int> Q;bool VIS[MAXN], Vis2[maxn];bool in[maxn];bool dfs (int cur, int root) {int sz = G[cur].size (); for (int i = 0; i < sz; i++) {int u = g[cur][i];if (In[u]) {if (Color[u]&&color[cur]!=6-color[root]-color[u]) r Eturn false;if (!vis2[u]) {if (!color[u]) color[u] = 6-color[cur]-Color[root];vis2[u] = 1;if (!dfs (U, root)) return Fals e;}}} return true;} int main () {freopen ("mayors.in", "R", stdin); Freopen ("Mayors.out", "w", stdout); Freopen ("Input.txt", "R", stdin); while (CIN >> n >> m) {for (int i = 0; i < m; i++) {int u, v; scanf ("%d%d", &u, & V); G[u].push_back (v); G[v].push_back (U); } bool tag = 1; int pos = 1;while (!q.empty () | | pos<= N) {if (Q.empty ()) {for (; pos<= N; pos++) {if (!vis[pos]) {Q.push (POS); color[pos ] = 1;vis[pos] = 1;break;}}} if (Q.empty ()) break;int u = Q.front (); Q.pop (); if (! G[u].size ()) continue;//cout << u << endl;memset (in, 0, sizeof (in)), memset (vis2, 0, sizeof (VIS2)); int start = g[u][0];for (int i = 0; i < g[u].size (); i++) {int v = g[u][i];if (!vis[v]) {Q.push (v); vis[v] = 1;} if (Color[v]) {start = V;} in[v] = 1;} if (!color[start]) Color[start] = 2;if (The!dfs (Start, u)) {puts ("Plan failed"); tag = 0;break;}} if (tag) {puts ("Plan OK"), for (int i = 1; I <= n; i++) printf ("%c", Mayor[color[i]]);p UTS ("");} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
GYM 100345E New Mayors (two-figure dyeing)