pc110901 Bicoloring (BFS)
|
![]() |
||||
![]() |
![]() |
![]() |
The four-color theoremstates that every planar map can be colored using only four colors in such a way that no region is colored using the same color as a neighbor. After being open for over 100 years, the theorem was proven in 1976 with the assistance of a computer.
Here you are asked to solve a simpler problem. Decide whether a given connected graph can be bicolored, i.e., can the vertices be painted red and black such that no two adjacent vertices have the same color.
To simplify the problem, you can assume the graph will be connected, undirected, and not contain self-loops (i.e., edges from a vertex to itself).
Input
The input consists of several test cases. Each test case starts with a line containing the number of vertices n, where 1 < n < 200. Each vertex is labeled by a number from 0 to n - 1. The second line contains the number of edges l. After this, llines follow, each containing two vertex numbers specifying an edge.
An input with n = 0marks the end of the input and is not to be processed.
Output
Decide whether the input graph can be bicolored, and print the result as shown below.
Sample Input
3 3 0 1 1 2 2 0 9 8 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0
Sample Output
NOT BICOLORABLE. BICOLORABLE.
分析:标记第一个点,周围的如果已经遍历过了判断是否符合条件,没有遍历和它异或;
3A 第一次CE 原因是memset()的 #inlcude<cstring> 我写成#include<string>
第二次TLE 原因是如果一个节点已经遍及过,我在判断是否符合条件时,没有加else,效果是如果遍历过但是符合条件我也进队了;

1 #include<iostream> 2 #include<cstring> 3 #include<queue> 4 #define N 200 5 using namespace std; 6 7 int map[N][N],a[N],n; 8 bool visited[N]; 9 10 bool BFS(int s) 11 { 12 queue<int>Q; 13 while(!Q.empty()) Q.pop(); 14 Q.push(s); 15 int i,t,flag; 16 flag=0; 17 while(!Q.empty()) 18 { 19 t=Q.front();Q.pop(); 20 visited[t]=true; 21 a[t]=flag;flag=flag^1; 22 for(i=0;i<n;i++) 23 { 24 if(map[t][i]==1) 25 { 26 if(visited[i]==true) 27 { 28 if(a[i]!=flag) return false; 29 } 30 else Q.push(i);//起初没有加else 31 } 32 } 33 } 34 return true; 35 } 36 37 int main() 38 { 39 int e,i,x,y; 40 while(cin>>n&&n) 41 { 42 cin>>e; 43 memset(map,0,sizeof(map)); 44 memset(visited,false,sizeof(visited)); 45 memset(a,-1,sizeof(a)); 46 for(i=0;i<e;i++) 47 { 48 cin>>x>>y; 49 map[x][y]=1; 50 } 51 if(BFS(0)) cout<<"BICOLORABLE."<<endl; 52 else cout<<"NOT BICOLORABLE."<<endl; 53 } 54 return 0; 55 }