UVA-140
题意:A:BC表示A和BC有连接。给出若干个类似提示,求给出的所有字母的一个序列,这个序列使得有连接2个字母之间的差值的最大值最小,若存在多个,取字典序最小的。
解题思路:要对所有字母判断是否是新的,新的要存起来。其实就是求全排列,然后求出距离差的最大值,看看是否比ans小。小就替换来。然后next_permutation是真的好用。
/*************************************************************************
> File Name: UVA-140.cpp
> Author: Narsh
>
> Created Time: 2016年07月28日 星期四 10时51分07秒
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
bool map[200][200],pd[200];
char c[30],temp,s[30],t;
int n,m,ans;
int main() {
freopen("xx.in","r",stdin);
while (scanf("%c",&temp) && temp != '#') {
n=0;
memset(pd,true,sizeof(pd));
memset(map,false,sizeof(map));
while (temp != '\n') {
if (pd[temp]) {
c[++n] = temp;
pd[temp] =false;
}
t = temp;
scanf("%c%c",&temp,&temp);
while (temp != ';' && temp != '\n') {
map[t][temp] = true;
map[temp][t] = true;
if (pd[temp]) {
c[++n]=temp;
pd[temp]=false;
}
scanf("%c",&temp);
}
if (temp != '\n') scanf("%c",&temp);
}
sort(c+1,c+1+n);
ans = 99999;
do{
m=0;
for (int i = 1; i <= n; i++)
for (int j = i+1; j <= n; j++)
if (map[c[i]][c[j]] && j-i > m) m = j-i;
if (m < ans) {
ans =m;
for (int i = 1; i <= n; i++)
s[i] = c[i];
}
}while (next_permutation(c+1,c+1+n));
for (int i = 1; i <= n; i++)
printf("%c ",s[i]);
printf("-> %d\n",ans);
}
}