合法的顺序一共有几种
七个构建任务编号 0~6,(a, b) 表示 a 做完才能做 b。
运行下面这段程序:
#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Edges = vector<pair<int, int>>;
const int N = 7;
// 七个构建任务,(a, b) 表示 a 做完才能做 b
const Edges DEP = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {4, 6}};
// 同一张图再加一条 5 → 3,于是有了环
const Edges G = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {5, 3}, {4, 6}};
// 枚举全部排列,数一数有几种不违反任何一条依赖
int topo_count(const Edges& edges, int n = N) {
vector<int> p(n);
iota(p.begin(), p.end(), 0);
int cnt = 0;
do {
vector<int> pos(n);
for (int i = 0; i < n; i++) pos[p[i]] = i;
bool ok = true;
for (auto [a, b] : edges) {
if (pos[a] > pos[b]) ok = false;
}
if (ok) cnt++;
} while (next_permutation(p.begin(), p.end()));
return cnt;
}
int main() {
cout << topo_count(DEP) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论