此题就是使用next_permutation
//
// main.cpp
// uva 140 - Bandwidth
//
// Created by XD on 15/7/27.
// Copyright (c) 2015年 XD. All rights reserved.
//
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
using namespace std ;
set<char> nodecache ;
set<char> graph[30] ;
int getMaxBi(char node[],int len)
{
int pos[27] ;
for (int i = 0; i < len ; i++) {
pos[node[i] - 'A'] = i ;
}
int maxb = -1 ;
for (set<char>::iterator it = nodecache.begin(); it!= nodecache.end(); it++) {
len = (int ) graph[*it - 'A'].size() ;
int tm = -1 ;
for (set<char>::iterator mit = graph[*it-'A'].begin(); mit!= graph[*it-'A'].end(); mit++) {
int b=abs(pos[*mit-'A'] - pos[*it-'A']);
tm = tm > b?tm :b ;
}
maxb = tm > maxb ? tm : maxb ;
}
return maxb ;
}
int main(int argc, const char * argv[]) {
char node[10] ;
char g[100] ;
int pos ;
int minb = 0 ;
while (scanf(" %s" , g )==1 && g[0]!='#') {
nodecache.clear() ;
for (int i = 0; i < 30; i++) {
graph[i].clear() ;
}
int len = (int )strlen(g) ;
for (int i = 0; i < len; i++) {
if (g[i] >= 'A' && g[i]<='Z') {
pos = g[i] - 'A' ;
nodecache.insert(g[i]) ;
i+=2 ;
while (i < len && g[i]!=';') {
nodecache.insert(g[i]) ;
graph[pos].insert(g[i]) ;
graph[g[i]-'A'].insert(pos + 'A') ;
i++ ;
}
}
}
int j = 0 ;
minb = 10 ;
char result[10] ;
for (set<char>::iterator it = nodecache.begin() ; it!=nodecache.end(); it++) {
node[j++] = *it ;
}
do{
int bandwidth = getMaxBi(node , j ) ;
if (minb > bandwidth) {
minb = bandwidth ;
for (int i = 0 ; i < j ; i++) {
result[i] = node[i] ;
}
}
}while (next_permutation(node, node+j)) ;
for (int i = 0; i < j ; i++) {
printf("%c " , result[i]) ;
}
printf("-> %d\n",minb) ;
}
return 0;
}