注意:本文只给出作者认为必要的知识点并且可能存在疏漏。 |
@
一、题目大意
给n个结点
(使用大写字母表示)
的无向图,要求枚举一个宽度最小的结点序列(宽度相同选字典序最小)
。其中,序列中结点V的宽度为其到序列中其他相连结点的距离的最大值,整个序列的宽度为所有结点宽度的最大值。
样例输入:A:FB;B:GC;D:GC;F:AGH;E:HD
样例输出:A B C F G D H E -> 3
二、理论基础
1. 回溯
详见:回溯法。
2. 最优性剪枝
在进行DFS遍历解答树时,若当前部分解已经比当前最优解差或相等时,继续遍历解答树只会浪费时间,立即停止搜索进行回溯。
三、解题思路
以邻接矩阵的形式存储图,记录出现的结点数和结点。对出现的结点存入一个数组并按字典序进行排序,进行递归枚举
(从头到尾遍历已求序列,第一个出现的邻接点与当前结点的距离为新求出的宽度,与已求的宽度进行对比取最大值)
。剪枝:当前序列的宽度已经大于或等于已得最小宽度时进行回溯。
四、参考代码
#include<bits/stdc++.h>
using namespace std;
#define maxn 26
#define INF 0x3f3f3f3f
typedef long long ll;
int G[maxn][maxn], ct[maxn], result[8], output[8], vis[maxn], n, r;
int nodes[maxn];
void dfs(int cur, int now) {
if (cur == n && r > now) {
r = now;
for (int i = 0; i < n; ++i)
output[i] = result[i];
} else if (now < r) {
for (int i = 0; i < n; ++i) {
int itemp = 0;
if (!vis[nodes[i]]) {
for (int j = 0; j < cur; j++)
if (G[nodes[i]][result[j]]) {
itemp = cur - j;
break;
}
itemp = max(itemp, now);
if (itemp > r)continue;
vis[nodes[i]] = 1;
result[cur] = nodes[i];
if (itemp <= r)
dfs(cur + 1, itemp);
vis[nodes[i]] = 0;
}
}
}
}
int main() {
ios::sync_with_stdio();
cin.tie(0), cout.tie(0);
string s, st;
s.reserve(700), st.reserve(maxn);
while (cin >> s && s[0] != '#') {
int head, itemp;
memset(G, 0, 2704);
memset(ct, 0, 104);
memset(vis, 0, 104);
r = INF, n = 0;
for (int i = 0; i < s.size(); ++i) {
head = s[i] - 'A', i++;;
if (s[i] != ':')break;
else {
itemp = ++i;
while (s[i] != ';' && s[i] != '\0') i++;
st = s.substr(itemp, i - itemp);
for (int j = 0; j < st.size(); j++) {
if (!G[head][st[j] - 'A']) {
ct[head]++;
G[head][st[j] - 'A'] = 1;
}
if (!G[st[j] - 'A'][head]) {
ct[st[j] - 'A']++;
G[st[j] - 'A'][head] = 1;
}
}
}
}
for (int i = 0; i < maxn; ++i)
if (ct[i])nodes[n++] = i;
sort(nodes, nodes + n);
dfs(0, 0);
cout << (char) (output[0] + 'A');
for (int i = 1; i < n; ++i)
cout << ' ' << (char)(output[i] + 'A');
cout << " -> " << r << endl;
}
return 0;
}