1154 Vertex Coloring (25point(s))
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 104), 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
题目大意:
输入 N 个点,M 条边的图,K 次检查,每次给出所有点的颜色,判断是否图的所有边的两端节点颜色不同
若所有边两端点颜色全不同,输出颜色的种数,否则输出 No
设计思路:
- 把图的所有边存起来
- 每次查询,遍历每条边,检查颜色
- 颜色的个数排序后去重
编译器:C (gcc)
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b)
{
return *((int *)a) - *((int *)b);
}
int get_cnt(int *a, int n)
{
int i, j;
qsort(a, n, sizeof(a[0]), cmp);
for (j = 1; j < n && a[j] != a[j - 1]; j++)
;
for (i = j - 1, j = j + 1; j < n; j++)
if (a[i] != a[j])
a[++i] = a[j];
return i + 1;
}
int main(void)
{
int n, m, k, e[10010][2], c[10010];
int i, j, f;
scanf("%d%d", &n, &m);
for (i = 0; i < m; i++)
scanf("%d %d", &e[i][0], &e[i][1]);
scanf("%d", &k);
while (k--) {
f = 1;
for (i = 0; i < n; i++)
scanf("%d", &c[i]);
for (i = 0; i < m; i++) {
if (c[e[i][0]] == c[e[i][1]]) {
f = 0;
break;
}
}
if (f)
printf("%d-coloring\n", get_cnt(c, n));
else
printf("No\n");
}
return 0;
}