UVA-140 Bandwidth

bandwith指在一个给定排列中 一个点与相连点的距离,所有点bandwith最大值为排列的bandwidth
给定节点和路径找出bandwidth排列,如果有多个排列bandwidth一样,输出字典序最小的一个
用一个vector保存路径,暴力枚举,找出所求排列
没想到没有优化直接枚举竟然不超时。。。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 string ans1;
 4 int ans2;
 5 int len(string s,char a,char b){
 6     int x,y;
 7     for(int i=0;i<s.length();i++){
 8         if(s[i]==a) x=i;
 9         if(s[i]==b) y=i;
10     }
11     return (x>y)?x-y:y-x;
12 }
13 void bandwidth(string s,vector<int>* board){
14     int ans=0;
15     for(int i=0;i<26;i++){
16         for(int j=0;j<26;j++){
17             if(board[i][j]==1){
18                 int l=len(s,i+'A',j+'A');
19                 if(l>ans){
20                     ans=l;
21                 }
22             }
23         }
24     }
25     if(ans<ans2){
26         ans2=ans;
27         ans1=s;
28     }
29 }
30 void dfs(string s,vector<int>* board,set<char>& node){
31     if(s.length()==node.size()){
32         bandwidth(s,board);
33     }
34     else {
35         s.resize(s.length()+1);
36         for(set<char>::iterator i=node.begin();i!=node.end();i++){
37             s[s.length()-1]=*i;
38             int ok=1;
39             for(int j=0;j<s.length()-1;j++)
40                 if((*i)==s[j]) ok=0;
41             if(ok){
42                 dfs(s,board,node);
43             }
44         }
45     }
46 }
47 int main()
48 {
49     string line;
50     stringstream ll;
51     while(getline(cin,line)&&line!="#"){
52         vector<int> board[26];
53         for(int i=0;i<26;i++) board[i].resize(26);
54         ll<<line;
55         char c;
56         set<char> node;
57         while(ll>>c){
58             char t=c;
59             node.insert(c);
60             ll>>c;
61             while(ll>>c&&c!=';'){
62                 board[c-'A'][t-'A']=board[t-'A'][c-'A']=1;
63                 node.insert(c);
64             }
65         }
66         ll.clear();
67         /*cout<<"  ";
68         for(int i=0;i<26;i++) cout<<(char)('A'+i)<<" ";
69         cout<<endl;
70         for(int i=0;i<26;i++){
71             cout<<(char)('A'+i)<<" ";
72             for(int j=0;j<26;j++)
73                 if(j==25) cout<<board[i][j]<<endl;
74                 else cout<<board[i][j]<<" ";
75         }*/
76         string s;
77         ans1.clear();
78         ans2=999;
79         dfs(s,board,node);
80         for(int i=0;i<ans1.length();i++){
81             cout<<ans1[i]<<" ";
82         }
83         cout<<"-> ";
84         cout<<ans2<<endl;
85     }
86     return 0;
87 }
原文地址:https://www.cnblogs.com/tooyoungtoosimple/p/4442900.html