Advertisement
Dmaxiya

洛谷 P2014 选课 参考代码

Mar 22nd, 2025
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 300 + 100;
  6. int n, m, k;
  7. int s[maxn];
  8. vector<int> G[maxn];
  9. int dp[maxn][maxn];
  10.  
  11. void dfs(int root) {
  12.     for (int pos : G[root]) {
  13.         dfs(pos);
  14.     }
  15.     for (int i = m; i >= 1; --i) {
  16.         dp[root][i] = s[root];
  17.     }
  18.     for (int pos : G[root]) {
  19.         for (int i = m; i >= 1; --i) {
  20.             for (int j = 1; j < i; ++j) {
  21.                 dp[root][i] = max(dp[root][i], dp[root][i - j] + dp[pos][j]);
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27. int main() {
  28. #ifdef ExRoc
  29.     freopen("test.txt", "r", stdin);
  30. #endif
  31.     ios::sync_with_stdio(false);
  32.  
  33.     cin >> n >> m;
  34.     ++m;
  35.     for (int i = 1; i <= n; ++i) {
  36.         cin >> k >> s[i];
  37.         G[k].push_back(i);
  38.     }
  39.     dfs(0);
  40.     cout << dp[0][m] << endl;
  41.  
  42.     return 0;
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement