#include <bits/stdc++.h> using namespace std; using ll = long long; int N, M, K; vector<vector<int>> deps; int solve(int k, const set<int>& without) { vector<int> length(N+1); vector<int> through(N+1); int longest = 0; for (int i = N; i >= 1; --i) { if (without.count(i)) continue; int len = 1; int thr = 0; for (int ne : deps[i]) { if (length[ne] + 1 >= len) { len = length[ne] + 1; thr = ne; } } length[i] = len; through[i] = thr; if (length[i] > length[longest]) { longest = i; } } if (k == 0) return length[longest]; int ans = length[longest]; for (int i = longest; i!=0; i = through[i]) { set<int> wc(without); wc.insert(i); int subans = solve(k-1, wc); if (subans < ans) ans = subans; } return ans; } int main() { cin >> N >> M >> K; deps.resize(N+1); for (int i = 0; i < M; ++i) { int x, y; cin >> x >> y; deps[x].push_back(y); } cout << solve(K, {}); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | #include <bits/stdc++.h> using namespace std; using ll = long long; int N, M, K; vector<vector<int>> deps; int solve(int k, const set<int>& without) { vector<int> length(N+1); vector<int> through(N+1); int longest = 0; for (int i = N; i >= 1; --i) { if (without.count(i)) continue; int len = 1; int thr = 0; for (int ne : deps[i]) { if (length[ne] + 1 >= len) { len = length[ne] + 1; thr = ne; } } length[i] = len; through[i] = thr; if (length[i] > length[longest]) { longest = i; } } if (k == 0) return length[longest]; int ans = length[longest]; for (int i = longest; i!=0; i = through[i]) { set<int> wc(without); wc.insert(i); int subans = solve(k-1, wc); if (subans < ans) ans = subans; } return ans; } int main() { cin >> N >> M >> K; deps.resize(N+1); for (int i = 0; i < M; ++i) { int x, y; cin >> x >> y; deps[x].push_back(y); } cout << solve(K, {}); return 0; } |