poj 1419 Graph Coloring 图着色有关问题
poj 1419 Graph Coloring 图着色问题
Graph Coloring
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 3829 | Accepted: 1710 | Special Judge |
Description
You are to write a program that tries to find an optimal coloring for a given graph. Colors are applied to the nodes of the graph and the only available colors are black and white. The coloring of the graph is called optimal if a maximum of nodes is black.
The coloring is restricted by the rule that no two connected nodes may be black.
Figure 1: An optimal graph with three black nodes
Figure 1: An optimal graph with three black nodes
Input
The graph is given as a set of nodes denoted by numbers 1...n, n <= 100, and a set of undirected edges denoted by pairs of node numbers (n1, n2), n1 != n2. The input file contains m graphs. The number m is given on the first line. The first line of each graph
contains n and k, the number of nodes and the number of edges, respectively. The following k lines contain the edges given by a pair of node numbers, which are separated by a space.
Output
The output should consists of 2m lines, two lines for each graph found in the input file. The first line of should contain the maximum number of nodes that can be colored black in the graph. The second line should contain one possible optimal coloring. It is
given by the list of black nodes, separated by a blank.
Sample Input
1 6 8 1 2 1 3 2 4 2 5 3 4 3 6 4 6 5 6
Sample Output
3 1 4 5
Source
Southwestern European Regional Contest 1995
对于这道图着色问题,在网上很多解法都是用回溯,一个一个来试探,然后判断当前的试探是否符合要求,而我的却完全不同。
下面说下我的思路:
存储结构:邻接矩阵
1.先对图上的点全部涂黑
2.按点遍历,找到与这点相联接的点,将联接的点涂成白色。
3.最后遍历一遍点计算黑点的数目即可。
考虑到最大的问题,所以应该让每个点都最先涂一次,以求得最优解。
下面是AC代码:
Source Code Problem: 1419 Memory: 304K Time: 16MS Language: C++ Result: Accepted Source Code
#include <iostream> #include <cstring> #include <cstdio> #define BLACK 0 #define WHITE 1 using namespace std; const int MAX=100+10; int n, k; int g[MAX][MAX]; int vis[MAX], color[MAX]; int ans=0; void init() { ans = 0; memset(color, BLACK, sizeof(color)); memset(g, 0, sizeof(g)); memset(vis,0, sizeof(vis)); } void read() { cin >> n >> k; int u, v; for(int i=1; i <= k; i++) { cin >> u >> v; g[u][v] = g[v][u] = 1; } } int writeWhite(int u) { int count=0; for(int i=u; i <= n+u-1; i++) { int pos = i%n; if(!pos) pos=n; if(color[pos]==BLACK) { count++; for(int v=1; v <= n; v++ ) if(g[pos][v]) color[v]=WHITE; } } return count; } void solve() { int ans=0; int resu[MAX]; for(int i=1; i <= n; i++) { memset(color, BLACK, sizeof(color)); int temp = writeWhite(i); if(temp > ans) { ans = temp; int length=0; for(int j=1; j <= n; j++) if(color[j]==BLACK) resu[length++]=j; } } cout << ans << endl; for(int i=0; i < ans; i++) cout << resu[i] <<" "; cout << endl; } int main() { // freopen("in.txt","r",stdin); int nCase; cin >> nCase; while(nCase--) { init(); read(); solve(); } return 0; }