Uva--140(暴力全排序)

本文介绍了一种解决图论中带宽最小化问题的方法。通过构建邻接矩阵并利用全排列寻找最优节点顺序,最终求得最小带宽值。代码采用C++实现,并详细展示了从输入到求解的全过程。

2014-07-17 12:46:32

题意&思路:给出图,建立邻接矩阵(数据量比较小,偷懒用下TAT),然后全排列,算出每种排列的最大bandwidth,最后取这些bandwidth的最小值即可。

这种类型的题目基本遵循:sort,do..while()格式。

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cmath>
 6 using namespace std;
 7 
 8 int g[30][30],s[8],used[30],tmin,tmax,cnt,len,a,b,Judge;
 9 char str[100];
10 
11 void Dfs(int cur){
12     if(cur >= cnt)
13         return;
14     for(int i = 0; i < 30; ++i)
15         if(g[s[cur]][i] == 1)
16             for(int j = 0; j < cnt; ++j)
17                 if(s[j] == i){
18                     tmax = max(tmax,abs(cur - j));
19                     break;
20                 }
21     Dfs(cur + 1);
22 }
23 
24 int main(){
25     while(scanf("%s",str) == 1){
26         if(str[0] == '#')
27             break;
28         len = strlen(str);
29         cnt = 0;
30         memset(s,0,sizeof(s));
31         memset(g,0,sizeof(g));
32         memset(used,0,sizeof(used));
33         int flag = 0;//0:wait,1:node
34         for(int i = 0; i < len; ++i){
35             if(flag == 0){
36                 flag = 1;
37                 a = str[i] - 'A';
38                 if(!used[a]){
39                     s[cnt++] = a;
40                     used[a] = 1;
41                 }
42             }
43             else if(flag == 1 && str[i] >= 'A' && str[i] <= 'Z'){
44                 b = str[i] - 'A';
45                 if(!used[b]){
46                     s[cnt++] = b;
47                     used[b] = 1;
48                 }
49                 g[a][b] = 1;
50                 g[b][a] = 1;
51             }
52             if(str[i] == ';')
53                 flag = 0;
54         }
55         sort(s,s + cnt);
56         tmin = 1000000000;
57         int ans[8];
58         do{
59             tmax = 0;
60             Dfs(0);
61             if(tmax < tmin){
62                 tmin = tmax;
63                 memcpy(ans,s,sizeof(s));
64             }
65         }while(next_permutation(s,s + cnt));
66         for(int i = 0; i < cnt; ++i){
67             printf("%c ",ans[i] + 'A');
68         }
69         printf("-> %d\n",tmin);
70     }
71     return 0;
72 }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值