pat 1154
1154Vertex Coloring(25分)
Aproper vertex coloringis 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 mostkcolors is called a (proper)k-coloring.
Now you are supposed to tell if a given coloring is a properk-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 1), 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 linek-coloring
k
-coloring for some positivek
, orNo
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
題意:給定一個圖,圖中每個頂點給一個顏色,要求一條邊兩端的頂點顏色不同。如果滿足要求,輸出使用的"顏色的數量-coloring",否則輸出No
思路:因為圖中頂點最多可以有10000個,用鄰接矩陣可能會超時(筆者沒試過),所以我採用的是鄰接表。讀入整個圖的資料之後,依次遍歷各條邊,看兩端的頂點顏色是否相同。相同則直接break輸出No,否則遍歷完所有頂點之後計算顏色數量輸出。
程式碼如下:
#include<cstdio> #include<vector> #include<set> using namespace std; vector<int> v[10005]; int n,m; int colors[10005]; void fun(){ int mark=0; for(int i=0;i<n;i++){ for(vector<int>::iterator it=v[i].begin();it!=v[i].end();it++){ if(colors[i]==colors[(*it)]){ mark=1; break; } } } if(mark==0){ set<int> s; for(int i=0;i<n;i++){ s.insert(colors[i]); } printf("%d-coloring\n",s.size()); } else printf("No\n"); } int main(){ int a,b; scanf("%d%d",&n,&m); for(int i=0;i<m;i++){ scanf("%d%d",&a,&b); v[a].push_back(b); v[b].push_back(a); } int k; scanf("%d",&k); for(int i=0;i<k;i++){ for(int j=0;j<n;j++){ scanf("%d",&colors[j]); } fun(); } return 0; }