bicoloring
|
Description
输入一个简单(无多重边和自环)的连通无向图,判断该图是否能用黑白两种颜色对顶点染色,使得每条边的两个端点为不同颜色。 Input
输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。 以下m行,每行是一个数对u v,表示存在边(u,v)。顶点编号从1开始。
Output
如果能做到双着色,输出"yes",否则输出"no"。 Sample Input
3 3 1 2 2 3 3 1 Sample Output
no |
|
View Code
1 // Problem#: 7056 2 // Submission#: 1805806 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University 6 #include <iostream> 7 #include <cstring> 8 #include <queue> 9 #include <vector> 10 using namespace std; 11 12 int color[1002]; //0表示未走, 1表示黑色,-1表示白色 13 bool visited[1002]; 14 vector<int>v[1002]; 15 int n, m; 16 queue<int>q; 17 18 bool bfs() 19 { 20 memset(color, 0, sizeof(color)); 21 memset(visited, false, sizeof(visited)); 22 23 color[1] = 1; 24 q.push(1); 25 while (!q.empty()){ 26 int a = q.front(); 27 q.pop(); 28 visited[a] = true; 29 int size = v[a].size(); 30 for (int i = 0; i < size; i++){ 31 int b = v[a][i]; 32 if (visited[b]) 33 continue; 34 if (color[a] != color[b]){ 35 color[b] = color[a] == -1 ? 1 : -1; 36 q.push(b); 37 } 38 else 39 return false; 40 } 41 } 42 return true; 43 } 44 45 int main() 46 { 47 cin >> n >> m; 48 int a, b; 49 for (int i = 0; i < m; i++){ 50 cin >> a >> b; 51 v[a].push_back(b); 52 v[b].push_back(a); 53 } 54 if (bfs()) 55 cout << "yes" << endl; 56 else 57 cout << "no" << endl; 58 //system("PAUSE"); 59 return 0; 60 }


浙公网安备 33010602011771号