#include <bits/stdc++.h> using namespace std; const int MAXN = 505; vector<int> v[MAXN]; int vis[MAXN]; int del[MAXN]; int dp[MAXN]; int tim = 1; int n; void path(int x) { if (vis[x] == tim) return; if (del[x] > 0) { dp[x] = 0; return; } vis[x] = tim; dp[x] = 1; for (int a : v[x]) { path(a); dp[x] = max(dp[x], 1+dp[a]); } } void updateDp() { tim++; for (int i=1; i<=n; i++) path(i); } int solve(int k) { vector<int> p; updateDp(); int l = 0; int st = 1; for (int i=1; i<=n; i++) { if (dp[i] > l) { l = dp[i]; st = i; } } if (k == 0) return l; p.push_back(st); while (dp[p.back()] > 1) { int next = -1; for (int a : v[p.back()]) { if (del[a] > 0) continue; if (dp[a] == dp[p.back()]-1) { next = a; break; } } p.push_back(next); } int res = l; for (int a : p) { del[a]++; res = min(res, solve(k-1)); del[a]--; } return res; } int main() { int m, k, a, b; scanf("%d%d%d", &n, &m, &k); for (int i=0; i<m; i++) { scanf("%d%d", &a, &b); v[a].push_back(b); } printf("%d\n", 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | #include <bits/stdc++.h> using namespace std; const int MAXN = 505; vector<int> v[MAXN]; int vis[MAXN]; int del[MAXN]; int dp[MAXN]; int tim = 1; int n; void path(int x) { if (vis[x] == tim) return; if (del[x] > 0) { dp[x] = 0; return; } vis[x] = tim; dp[x] = 1; for (int a : v[x]) { path(a); dp[x] = max(dp[x], 1+dp[a]); } } void updateDp() { tim++; for (int i=1; i<=n; i++) path(i); } int solve(int k) { vector<int> p; updateDp(); int l = 0; int st = 1; for (int i=1; i<=n; i++) { if (dp[i] > l) { l = dp[i]; st = i; } } if (k == 0) return l; p.push_back(st); while (dp[p.back()] > 1) { int next = -1; for (int a : v[p.back()]) { if (del[a] > 0) continue; if (dp[a] == dp[p.back()]-1) { next = a; break; } } p.push_back(next); } int res = l; for (int a : p) { del[a]++; res = min(res, solve(k-1)); del[a]--; } return res; } int main() { int m, k, a, b; scanf("%d%d%d", &n, &m, &k); for (int i=0; i<m; i++) { scanf("%d%d", &a, &b); v[a].push_back(b); } printf("%d\n", solve(k)); return 0; } |