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 }

转载于:https://www.cnblogs.com/naturepengchen/articles/3850913.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值