解題思路
先把八個名字按字典序排序,依此順序枚舉所有 8! 個排列。建立每頭牛在候選排列的位置表。
對每條限制檢查兩頭牛的位置差絕對值是否為 1。第一個全部通過的排列必定最小,因為此前所有更小的排列都已被排除。
時間 O(8!·(8+N)),空間 O(8+N)。
Step-by-step animation
獨立單限制示意:Beatrice 必須緊鄰 Sue
步驟 1 / 3
先排序
名字按照字典序排列。
Beatrice
Belinda
Bella
Bessie
Betsy
Blue
Buttercup
Sue
- 候選數
- 40320
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> a = {"Bessie", "Buttercup", "Belinda", "Beatrice",
"Bella", "Blue", "Betsy", "Sue"};
sort(a.begin(), a.end());
vector<pair<string, string>> e;
while (n--) {
string x, y, t;
cin >> x >> t >> t >> t >> t >> y;
e.push_back({x, y});
}
do {
map<string, int> pos;
for (int i = 0; i < 8; i++)
pos[a[i]] = i;
bool ok = 1;
for (auto [x, y] : e)
if (abs(pos[x] - pos[y]) != 1)
ok = 0;
if (ok) {
for (auto x : a)
cout << x << '\n';
break;
}
} while (next_permutation(a.begin(), a.end()));
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。