#include <cstdio> #include <vector> #include <limits> #include <set> using namespace std; vector<int> FindLongest(const vector<vector<int>>& e, set<int>& v) { vector<pair<int, int>> p(e.size(), make_pair(-1, -1)); pair<int, int> start = make_pair(-1, -1); for (int i=e.size()-1; i>=0; --i) { if (v.find(i) != v.end()) continue; p[i] = make_pair(0, -1); for (int j : e[i]) { if (p[j].first + 1 > p[i].first) { p[i] = make_pair(p[j].first + 1, j); } } if (p[i].first > start.first) { start = make_pair(p[i].first, i); } } vector<int> longest; while (start.second != -1) { longest.push_back(start.second); start = p[start.second]; } return longest; } vector<int> FindLongestRecursively(const vector<vector<int>>& e, set<int> v, int k) { vector<int> longest = FindLongest(e, v); if (k == 0) return longest; bool initialized = false; vector<int> result; for (int i : longest) { v.insert(i); vector<int> curr = FindLongestRecursively(e, v, k-1); v.erase(i); if (!initialized || curr.size() < result.size()) { initialized = true; result = curr; } } return result; } int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<vector<int>> e(n); for (int i=0; i<m; ++i) { int x, y; scanf("%d %d", &x, &y); --x; --y; e[x].push_back(y); } vector<int> longest = FindLongestRecursively(e, set<int>(), k); printf("%d\n", (int)longest.size()); 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 | #include <cstdio> #include <vector> #include <limits> #include <set> using namespace std; vector<int> FindLongest(const vector<vector<int>>& e, set<int>& v) { vector<pair<int, int>> p(e.size(), make_pair(-1, -1)); pair<int, int> start = make_pair(-1, -1); for (int i=e.size()-1; i>=0; --i) { if (v.find(i) != v.end()) continue; p[i] = make_pair(0, -1); for (int j : e[i]) { if (p[j].first + 1 > p[i].first) { p[i] = make_pair(p[j].first + 1, j); } } if (p[i].first > start.first) { start = make_pair(p[i].first, i); } } vector<int> longest; while (start.second != -1) { longest.push_back(start.second); start = p[start.second]; } return longest; } vector<int> FindLongestRecursively(const vector<vector<int>>& e, set<int> v, int k) { vector<int> longest = FindLongest(e, v); if (k == 0) return longest; bool initialized = false; vector<int> result; for (int i : longest) { v.insert(i); vector<int> curr = FindLongestRecursively(e, v, k-1); v.erase(i); if (!initialized || curr.size() < result.size()) { initialized = true; result = curr; } } return result; } int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<vector<int>> e(n); for (int i=0; i<m; ++i) { int x, y; scanf("%d %d", &x, &y); --x; --y; e[x].push_back(y); } vector<int> longest = FindLongestRecursively(e, set<int>(), k); printf("%d\n", (int)longest.size()); return 0; }; |