PAT 1154 Vertex Coloring
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
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
For each coloring, print in a line k-coloring if it is a proper k-coloring for some positive k, or No if not.
Examples
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-coloring为有k种不同的颜色的图, 输出k, 如果不满足则输出No
题解:
之前好多都是遍历整个图, 结果是N^2复杂度, 其实这道题只需要遍历边就可以了, 然后用set存一下颜色, 最后输出数量就行了
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const LL maxn = 1e4+10;
int N, M, k, color[maxn], ans;
struct edge{int from, to;};
edge E[maxn];
set<int> used; //当前出现的颜色;
bool check(){
for(int i = 1; i <= M; i++)
if(color[E[i].from] == color[E[i].to])
return false;
ans = used.size();
return true;
}
int main()
{
cin >> N >> M;
int a, b;
for(int i = 1; i <= M; i++)
cin >> E[i].from >> E[i].to;
cin >> k;
while(k--){
ms(color, 0); used.clear();
for(int i = 0; i < N; i++){
cin >> color[i];
used.insert(color[i]);
}
if(check()) cout << ans << "-coloring" << endl;
else cout << "No" << endl;
}
return 0;
}