Salvens

A

Jul 31st, 2023
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <array>
  4. #include <set>
  5.  
  6. using namespace std;
  7.  
  8. #define int long long
  9.  
  10. const long long INF = 1e18 + 7;
  11. const int MAXN = 6e3 + 100;
  12. const int N = 1e5 + 10;
  13.  
  14. array<array<int, MAXN>, 2> dp;
  15. array<int, MAXN> cost;
  16. vector<vector<int>> g;
  17.  
  18. void dfs(int v) {
  19.     for (auto to: g[v]) {
  20.         dfs(to);
  21.         dp[0][v] += max(dp[0][to], dp[1][to]);
  22.         dp[1][v] += dp[0][to];
  23.     }
  24.     dp[1][v] += cost[v];
  25. }
  26.  
  27. signed main() {
  28.     ios_base::sync_with_stdio(false);
  29.     cin.tie(nullptr);
  30.     cout.tie(nullptr);
  31.     int n;
  32.     cin >> n;
  33.     for (int i = 0; i < n; ++i) {
  34.         cin >> cost[i];
  35.     }
  36.     g.resize(n);
  37.     set<int> st;
  38.     for(int i = 0; i < n; ++i) {
  39.         st.insert(i);
  40.     }
  41.     while (true) {
  42.         int u, v;
  43.         cin >> u >> v;
  44.         if (u == 0 && v == 0) {
  45.             break;
  46.         }
  47.         --u, --v;
  48.         g[v].emplace_back(u);
  49.         st.erase(u);
  50.     }
  51.     int root = *st.begin();
  52.     dfs(root);
  53.     cout << max(dp[0][root], dp[1][root]) << '\n';
  54. }
Advertisement
Add Comment
Please, Sign In to add comment