Uva--140(暴力全排序)

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 }
posted @ 2014-07-17 12:49  Naturain  阅读(135)  评论(0编辑  收藏  举报