UVA 蹦了 不知道能不能过 先写上在说,不对在改吧!
思路很简单:
直接从输入中建立出一张图,然后全排列枚举图,在每一个全排列中遍历带宽
最后更新答案!
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<cctype>
using namespace std;
const int maxn = 200 + 10;
const int INF = 1e9;
vector<int>v[30];
char s[maxn];
int a[30];
int main(){
while(scanf("%s",s+1) == 1 && s[1] != '#'){
s[0] = ';';
int len = strlen(s);
s[len++] = ';';
s[len] = 0;
for (int i = 0; i < 26; ++i)v[i].clear();
for (int i = 0; i < len; ++i){
if (s[i] == ';'){
int u = s[i+1]-'A',j;
for (j = i + 3; j < len && s[j] != ';'; ++j){
int vv = s[j] - 'A';
v[u].push_back(vv);
v[vv].push_back(u);
}
i = j - 1;
}
}
int cnt = 0;
for (int i = 0; i < 26; ++i)if (!v[i].empty())a[cnt++] = i;
sort(a,a+cnt);
int aa[10];
int ans = INF;
do{
int pos[10];
int band = 0;
for (int i = 0; i < cnt; ++i)pos[a[i]] = i;
for (int i = 0; i < cnt; ++i){
int u = a[i];
for (int j = 0; j < v[u].size(); ++j){
band = max(band,abs(pos[v[u][j]]-pos[u]));
}
}
if (band < ans){
ans=band;
memcpy(aa,a,sizeof(int)*10);
}
}while(next_permutation(a,a+cnt));
for (int i = 0; i < cnt; ++i)printf("%c ",aa[i] + 'A');
printf("-> %d\n",ans);
}
return 0;
}