UVA 10004-Bicoloring
题目大意:给0~n的格子,以及哪些格子相连,问能否用俩种颜色涂格子使相连个字颜色不同
解题思路:用栈记录相连格子以及记录个字颜色,dfs搜索,如果颜色与上回涂色不同则返回0
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
int m;
int n;
int col[1000];
stack<int> sta[1000];
int dfs(int a) {
while(!sta[a].empty()) {
int c = sta[a].top();
if(col[c] != 0) {
if(3 - col[c] != col[a])
return 0;
}
else {
col[c] = 3 - col[a];
int b = dfs(c);
if(b == 0)
return 0;
else
return 1;
}
sta[a].pop();
}
return 1;
}
int main() {
while(cin >> n && n != 0) {
for(int i = 0; i < n; i++)
if(!sta[i].empty())
sta[i].pop();
cin >> m;
for(int i = 0; i < m; i++) {
int x, y;
cin >> x;
cin >> y;
sta[x].push(y);
}
memset(col, 0, sizeof(col));
col[0] = 1;
int s = dfs(0);
if(s == 0)
printf("NOT BICOLORABLE.\n");
else
printf("BICOLORABLE.\n");
}
return 0;
}