#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define PB push_back #define ST first #define ND second const int maxn = 320; vector<int> v[maxn]; int n; int d[maxn], val[maxn], p[maxn]; bool cur[maxn]; int rec(int k) { for(int i=1; i <= n; i++) d[i] = 0; for(int i=1; i <= n; i++) if(cur[i] == false) for(int b : v[i]) d[b]++; queue<int> q; for(int i=1; i <= n; i++) { if(cur[i]) continue; if(d[i] == 0) q.push(i); val[i] = 1; p[i] = -1; } while(q.empty() == false) { int a = q.front(); q.pop(); for(int b : v[a]) { if(cur[b]) continue; d[b]--; if(d[b] == 0) q.push(b); if(val[a]+1 > val[b]) { val[b] = val[a]+1; p[b] = a; } } } int maxd=0, maxi=0; for(int i=1; i <= n; i++) { if(cur[i]) continue; if(val[i] > maxd) { maxd = val[i]; maxi = i; } } if(maxd == 0) return 0; if(k == 0) return maxd; vector<int> t; int a = maxi; t.PB(a); while(p[a] != -1) { a = p[a]; t.PB(a); } int res=maxd; for(int b : t) { cur[b] = true; int x = rec(k-1); //cout << b << " " << x << endl; res = min(res, x); cur[b] = false; } return res; } int main() { ios_base::sync_with_stdio(0); int m, k; cin >> n >> m >> k; while(m--) { int a, b; cin >> a >> b; v[a].PB(b); } cout << rec(k) << "\n"; 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 98 99 100 101 102 103 | #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define PB push_back #define ST first #define ND second const int maxn = 320; vector<int> v[maxn]; int n; int d[maxn], val[maxn], p[maxn]; bool cur[maxn]; int rec(int k) { for(int i=1; i <= n; i++) d[i] = 0; for(int i=1; i <= n; i++) if(cur[i] == false) for(int b : v[i]) d[b]++; queue<int> q; for(int i=1; i <= n; i++) { if(cur[i]) continue; if(d[i] == 0) q.push(i); val[i] = 1; p[i] = -1; } while(q.empty() == false) { int a = q.front(); q.pop(); for(int b : v[a]) { if(cur[b]) continue; d[b]--; if(d[b] == 0) q.push(b); if(val[a]+1 > val[b]) { val[b] = val[a]+1; p[b] = a; } } } int maxd=0, maxi=0; for(int i=1; i <= n; i++) { if(cur[i]) continue; if(val[i] > maxd) { maxd = val[i]; maxi = i; } } if(maxd == 0) return 0; if(k == 0) return maxd; vector<int> t; int a = maxi; t.PB(a); while(p[a] != -1) { a = p[a]; t.PB(a); } int res=maxd; for(int b : t) { cur[b] = true; int x = rec(k-1); //cout << b << " " << x << endl; res = min(res, x); cur[b] = false; } return res; } int main() { ios_base::sync_with_stdio(0); int m, k; cin >> n >> m >> k; while(m--) { int a, b; cin >> a >> b; v[a].PB(b); } cout << rec(k) << "\n"; return 0; } |