UVa 140 - Bandwidth(回溯)
2015-03-04 23:51
295 查看
一道回溯的练习题, 输入有点麻烦。
#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; }
相关文章推荐
- Uva140 Bandwidth 【dfs回溯+剪枝】【例题7-6】
- UVA 140 - Bandwidth 暴力 全排列 回溯
- UVA-140 Bandwidth (回溯+剪枝)
- UVA - 140 Bandwidth: 暴力 回溯
- UVa 140 Bandwidth(DFS 回溯 剪枝)
- UVA 140 Brandwidth 带宽 (dfs回溯)
- uva 140 bandwidth (好题) ——yhx
- uva140-Bandwidth
- uva 140 Bandwidth
- UVa 140 - Bandwidth
- UVA 140 Bandwidth 暴力模拟
- UVa - 140 - Bandwidth
- uva 140 Bandwidth(全排列+递归)
- UVA 140 Bandwidth
- Bandwidth UVA - 140(next_premutation)
- UVA 140 BandWidth
- 带宽(Bandwidth,UVa 140)
- UVa 140 - Bandwidth
- UVa 140 - Bandwidth(全排列+回溯剪枝)
- UVa - 140 - Bandwidth