网址如下:
Bandwidth - UVA 140 - Virtual Judge (vjudge.net)
(第三方网站)
现在回想一下,我用的IDcache法好像不如用一个集合记录本次出现的结点来用
这样就可以按照字典序遍历,只有遇到带宽更小的才复制,就不用考虑带宽相等时比较字典序的问题了
代码如下:
#include<cstdio>
#include<vector>
#include<map>
#include<cstring>
#include<cctype>
using namespace std;
const int maxwid = 70;
const int maxnode = 8;
int ans[maxnode], A[maxnode], minwid = maxwid, cnt;
char c_ans[maxnode];
bool G[maxnode][maxnode], vis[maxnode];
vector<char> Ccache;
map<char, int> IDcache;int ID(char c){if(IDcache.count(c)) return IDcache[c];Ccache.push_back(c);return IDcache[c] = Ccache.size() - 1;
}
bool scanf_input(void){char c = getchar(); if(c == '#') return false;do{char u = c; getchar();while(isalpha(c = getchar())){char v = c;G[ID(u)][ID(v)] = G[ID(v)][ID(u)] = true;}}while((c != '\n') && (c = getchar()));cnt = Ccache.size();return true;
}
void get_ans(int cur, int wid){for(int i = 0; i < cur - 1; i++){if(G[A[i]][A[cur - 1]]) wid = (wid > cur - i - 1) ? wid : cur - i - 1;if(wid > minwid) return;}if(cur == cnt){char c_A[maxnode];for(int i = 0; i < cnt; i++) c_A[i] = Ccache[A[i]];if(minwid == wid){if(memcmp(c_ans, c_A, sizeof(c_A)) > 0){memcpy(c_ans, c_A, sizeof(c_A)); memcpy(ans, A, sizeof(A));}}else{minwid = wid; memcpy(c_ans, c_A, sizeof(c_A)); memcpy(ans, A, sizeof(A));}}else{for(int i = 0; i < cnt; i++)if(!vis[i]){A[cur] = i;vis[i] = true;get_ans(cur + 1, wid);vis[i] = false;}}
}//记得考虑字典序
void print_ans(void){for(int i = 0; i < cnt; i++){if(i) putchar(' ');printf("%c", Ccache[ans[i]]);}printf(" -> %d\n", minwid);
}
inline void initialize(void){memset(G, 0, sizeof(G)); memset(vis, 0, sizeof(vis)); minwid = maxwid;Ccache.clear(); IDcache.clear();
}int main(void)
{while(scanf_input()){get_ans(0, 0);print_ans();initialize();}return 0;
}