#include <bits/stdc++.h> using namespace std; const int N = 305; int n, m, k, dp[N], gdz[N]; vector<int> adj[N], topo; bool vis[N], block[N]; void dfs(int v) { vis[v] = 1; for (auto u: adj[v]) if (!vis[u]) dfs(u); topo.push_back(v); } int licz() { for (int i = n-1; i >= 0; i--) { int v = topo[i]; dp[v] = 1; gdz[v] = -1; for (auto u: adj[v]) if (!block[u]) if (dp[v] < dp[u] + 1) { dp[v] = dp[u] + 1; gdz[v] = u; } } int res = 0; for (auto v: topo) if (!block[v]) res = max(res, dp[v]); return res; } int rek(int l) { int x = licz(); if (l == 0) return x; vector<int> path; int st = -1; for (auto v: topo) if (dp[v] == x && !block[v]) st = v; while (st != -1) { path.push_back(st); st = gdz[st]; } int result = n+1; for (auto v: path) { block[v] = 1; result = min(result, rek(l-1)); block[v] = 0; } return result; } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); adj[u].push_back(v); } for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i); reverse(topo.begin(), topo.end()); printf("%d\n", rek(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 | #include <bits/stdc++.h> using namespace std; const int N = 305; int n, m, k, dp[N], gdz[N]; vector<int> adj[N], topo; bool vis[N], block[N]; void dfs(int v) { vis[v] = 1; for (auto u: adj[v]) if (!vis[u]) dfs(u); topo.push_back(v); } int licz() { for (int i = n-1; i >= 0; i--) { int v = topo[i]; dp[v] = 1; gdz[v] = -1; for (auto u: adj[v]) if (!block[u]) if (dp[v] < dp[u] + 1) { dp[v] = dp[u] + 1; gdz[v] = u; } } int res = 0; for (auto v: topo) if (!block[v]) res = max(res, dp[v]); return res; } int rek(int l) { int x = licz(); if (l == 0) return x; vector<int> path; int st = -1; for (auto v: topo) if (dp[v] == x && !block[v]) st = v; while (st != -1) { path.push_back(st); st = gdz[st]; } int result = n+1; for (auto v: path) { block[v] = 1; result = min(result, rek(l-1)); block[v] = 0; } return result; } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); adj[u].push_back(v); } for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i); reverse(topo.begin(), topo.end()); printf("%d\n", rek(k)); return 0; } |