Uva--192(回溯)
2014-07-17 14:01:32
题意&思路:无向有环图的染色问题,直接DFS回溯。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 7 int m,n,k,tmax,g[100][100],c[100],ans[100] = {0}; 8 9 void Dfs(int cur,int sum){ 10 if(cur >= n){ 11 if(sum > tmax){ 12 tmax = sum; 13 memcpy(ans,c,sizeof(c)); 14 } 15 return; 16 } 17 int judge = 1; 18 for(int i = 0; i < n; ++i){ 19 if(g[cur][i] == 1 && c[i] == 1){ 20 judge = 0; 21 break; 22 } 23 } 24 if(cur == 0 || judge){ 25 c[cur] = 1; 26 Dfs(cur + 1,sum + 1); 27 } 28 c[cur] = 0; 29 Dfs(cur + 1,sum); 30 } 31 32 int main(){ 33 int a,b; 34 scanf("%d",&m); 35 while(m--){ 36 memset(g,0,sizeof(g)); 37 memset(c,0,sizeof(c)); 38 scanf("%d %d",&n,&k); 39 while(k--){ 40 scanf("%d %d",&a,&b); 41 g[a - 1][b - 1] = 1; 42 g[b - 1][a - 1] = 1; 43 } 44 tmax = 0; 45 Dfs(0,0); 46 printf("%d\n",tmax); 47 int head = 1; 48 for(int i = 0; i < n; ++i){ 49 if(ans[i]){ 50 if(head){ 51 printf("%d",i + 1); 52 head = 0; 53 } 54 else printf(" %d",i + 1); 55 } 56 } 57 puts(""); 58 } 59 return 0; 60 }