Given a graph (V,E) where V is a set of nodes and E is a set of arcs in VxV, and an ordering on the elements in V, then the bandwidth of a node v is defined as the maximum distance in the ordering between v and any node to which it is connected in the graph. The bandwidth of the ordering is then defined as the maximum of the individual bandwidths. For example, consider the following graph:
This can be ordered in many ways, two of which are illustrated below:
For these orderings, the bandwidths of the nodes (in order) are 6, 6, 1, 4, 1, 1, 6, 6 giving an ordering bandwidth of 6, and 5, 3, 1, 4, 3, 5, 1, 4 giving an ordering bandwidth of 5.
Write a program that will find the ordering of a graph that minimises the bandwidth.
Input will consist of a series of graphs. Each graph will appear on a line by itself. The entire file will be terminated by a line consisting of a single #. For each graph, the input will consist of a series of records separated by ‘;’. Each record will consist of a node name (a single upper case character in the the range ‘A’ to ‘Z’), followed by a ‘:’ and at least one of its neighbours. The graph will contain no more than 8 nodes.
Output will consist of one line for each graph, listing the ordering of the nodes followed by an arrow (->) and the bandwidth for that ordering. All items must be separated from their neighbours by exactly one space. If more than one ordering produces the same bandwidth, then choose the smallest in lexicographic ordering, that is the one that would appear first in an alphabetic listing.
A:FB;B:GC;D:GC;F:AGH;E:HD
#
A B C F G D H E -> 3
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 10;
int id[256], letter[maxn];
int main() {
char input[1000];
while(scanf("%s", input) == 1 && input[0] != '#') {
// 计算结点个数并给字母编号
int n = 0;
for(char ch = 'A'; ch <= 'Z'; ch++)
if(strchr(input, ch) != NULL) {
// id['A'] = 0 依次类推
id[ch] = n++;
// letter[0] = 'A' 依次类推
letter[id[ch]] = ch;
}
// 处理输入
int len = strlen(input), p = 0, q = 0;
vector<int> u, v;
for(;;) {
while(p < len && input[p] != ':') p++;
if(p == len) break;
while(q < len && input[q] != ';') q++;
for(int i = p+1; i < q; i++) {
// u[i]->v[i]为邻接边
// 找到顶点
u.push_back(id[input[p-1]]);
// 找到邻接点
v.push_back(id[input[i]]);
}
p++; q++;
}
// 枚举全排列
int P[maxn], bestP[maxn], pos[maxn], ans = n;
for(int i = 0; i < n; i++) P[i] = i;
do {
for(int i = 0; i < n; i++) pos[P[i]] = i; // 每个字母的位置
int bandwidth = 0;
for(int i = 0; i < u.size(); i++)
bandwidth = max(bandwidth, abs(pos[u[i]] - pos[v[i]])); // 计算带宽
if(bandwidth < ans) {
ans = bandwidth;
memcpy(bestP, P, sizeof(P));
}
} while(next_permutation(P, P+n));
// 输出
for(int i = 0; i < n; i++) printf("%c ", letter[bestP[i]]);
printf("-> %d\n", ans);
}
return 0;
}