题意:给出了图的结点的一些的连通情况,让输出图结点的某种排列方式可以时所有联结的两结点的在这种线性排列方式下距离最长的长度是在所有排列方式内最短,然后输出这种序列并输出此时最长的距离。
题解:将这些结点全排列,然后选出长度最小的输出。
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 8;
const int INF = 10;
string str;
int m[26], g[26][26], n, res[N], ans, maxx;
char temp[N];
void init() {
memset(m, 0, sizeof(m));
memset(g, 0, sizeof(n));
ans = INF;
}
int main() {
char c;
int i, j;
while (cin >> str && str[0] != '#') {
init();
memset(m, 0, sizeof(m));
memset(g, 0, sizeof(g));
int len = str.size();
for (i = 0; i < len; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
m[str[i] - 'A'] = 1;
}
for (j = i + 2; j < len; j++) {
if (str[j] >= 'A' && str[j] <= 'Z') {
g[str[j] - 'A'][str[i] - 'A'] = g[str[i] - 'A'][str[j] - 'A'] = 1;
m[str[j] - 'A'] = 1;
}
else
break;
}
i = j;
}
n = 0;
for (int i = 0; i < 26; i++) {
if (m[i] == 1)
temp[n++] = i + 'A';
}
do {
maxx = -1;
int count;
for (int cur = 0; cur < n; cur++) {
for (int v = 0; v < 26; v++)
if (g[temp[cur] - 'A'][v]) {
for (int i = 0; i < n; i++)
if (temp[i] == v + 'A') {
count = i - cur;
break;
}
if (count > maxx)
maxx = count;
}
}
if (maxx < ans) {
ans = maxx;
for (int i = 0; i < n; i++)
res[i] = temp[i];
}
} while (next_permutation(temp, temp + n));
for (int i = 0; i < n; i++)
printf("%c ", res[i]);
printf("-> %d\n", ans);
}
return 0;
}