A proper vertex coloring is a labeling of the graph’s vertices with colors such that no two vertices sharing the same edge have the same color. A coloring using at most k colors is called a (proper) k-coloring.
Now you are supposed to tell if a given coloring is a proper k-coloring.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (both no more than 10
4
), being the total numbers of vertices and edges, respectively. Then M lines follow, each describes an edge by giving the indices (from 0 to N−1) of the two ends of the edge.
After the graph, a positive integer K (≤ 100) is given, which is the number of colorings you are supposed to check. Then K lines follow, each contains N colors which are represented by non-negative integers in the range of int. The i-th color is the color of the i-th vertex.
Output Specification:
For each coloring, print in a line k-coloring if it is a proper k-coloring for some positive k, or No if not.
Sample Input:
10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
4
0 1 0 1 4 1 0 1 3 0
0 1 0 1 4 1 0 1 0 0
8 1 0 1 4 1 0 5 3 0
1 2 3 4 5 6 7 8 8 9
Sample Output:
4-coloring
No
6-coloring
No
题目大意:给定一个图和k个问题。对于每个问题,给每个点染色,然后判断这个图是否任意相邻两点之间颜色都不同。若是,输出颜色个数;否则,输出No。
os:我一开始是用邻接表存图,然后通过bfs来求解。。。结果颜色的计数搞得麻烦的要死,思路也不够清晰,最后结果也只有18分。。。参考了以下柳神的代码,觉得好简洁,思路也很清晰,就理解了一下然后用自己的方式敲了出来。
思路:这个题实际上并不需要去存图。题目的最主要要求就是要判断每相邻两边是否同色,那么我们只存边就行了。
- 用一个二维数组e[ ][2]去存边
- 用color[ ]表示每个点的颜色
- 用set去记录颜色的个数
然后判断每条边的两个点即可。
代码如下:
#include <iostream>
#include <set>
#define maxn 10001
using namespace std;
int main()
{
int n, m, i;
int e[maxn][2], color[maxn];
set<int>s;
cin >> n >> m;
for(i = 1; i <= m; i++) cin >> e[i][0] >> e[i][1];
int k;
cin >> k;
while(k--)
{
s.clear();//每次判断结束之后,要清空以下,以免影响下一次判断
for(i = 0; i < n; i++)
{
cin >> color[i];
s.insert(color[i]);
}
for(i = 1; i <= m; i++)
{
if(color[e[i][0]] == color[e[i][1]])//如果存在一条边邻接点同色,直接退出
break;
}
if(i == m+1) cout << s.size() << "-coloring" << endl;
else cout << "No" << endl;
}
return 0;
}
总结
- 对于要去重的计数问题,果断用set。
- 和图有关的问题,先考虑一下是否有必要去存图