一道回溯的练习题, 输入有点麻烦。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <map>
#include <set>
#define MAXN 110
using namespace std;
char s[MAXN], str[MAXN], A[MAXN];
int cnt, best_k, k;
int per[MAXN], best_sort[MAXN], G[MAXN][MAXN];
int best_sov() {
k = 0;
for(int i = 0; i < cnt; i++)
for(int j = 0; j < cnt; j++)
if(G[A[per[i]] - 'A'][A[per[j]] - 'A']) {
k = max(k, abs(j - i));
if(best_k&& k > best_k) return best_k;
}
return k;
}
void all_per(int cur) {
if(cur == cnt) {
if(!best_k) {
best_k = best_sov();
for(int i = 0; i < cnt; i++)
best_sort[i] = per[i];
} else if(best_sov() < best_k) {
best_k = best_sov();
for(int i = 0; i < cnt; i++)
best_sort[i] = per[i];
}
} else for(int i = 0; i < cnt; i++) {
bool ok = true;
for(int j = 0; j < cur; j++) {
if(per[j] == i) {ok = false; break;}
}
if(ok) {
per[cur] = i;
all_per(cur + 1);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
while (cin >> str&& str[0] != '#') {
int cur = -1, n = 0, j = 0;
set<char> letter;
for(int i = 0; i < strlen(str); i++) {
if(isalpha(str[i]))
s[n++] = str[i];
if(str[i] == ':')
cur = str[i - 1] - 'A';
if(str[i] == ';')
cur = -1;
if(cur != -1&& isalpha(str[i]))
G[cur][str[i] - 'A'] = 1;
}
sort(s, s + n);
for(int i = 0; i < n; i++)
if(!letter.count(s[i])) {
A[j++] = s[i];
letter.insert(s[i]);
}
cnt = j;
best_k = 0;
all_per(0);
for(int i = 0; i < cnt; i++) {
if(i) printf(" ");
printf("%c", A[best_sort[i]]);
}
printf(" -> %d\n", best_k);
memset(G, 0, sizeof(G));
}
return 0;
}