Advertisement
erek1e

POI Task FarmCraft

Jul 6th, 2023
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. vector<int> c;
  8. vector<vector<int>> g;
  9.  
  10. // returns pair (t, c)
  11. // t = time spent in subtree, c = time after entering subtree that all nodes are installed
  12. pair<int, long long> dfs(int node, int parent = -1) {
  13.     vector<pair<int, long long>> v;
  14.     for (int child : g[node]) {
  15.         if (child == parent) continue;
  16.         pair<int, long long> pr = dfs(child, node);
  17.         pr.first += 2, pr.second += 1;
  18.         v.push_back(pr);
  19.     }
  20.     sort(v.begin(), v.end(), [](const pair<int, long long> &a, const pair<int, long long> &b) {
  21.         return a.first-a.second < b.first-b.second; // sort by t-c
  22.     });
  23.     int sumT = 0;
  24.     long long maxSetup = 0;
  25.     for (size_t i = 0; i < v.size(); sumT += v[i++].first) {
  26.         maxSetup = max(maxSetup, sumT + v[i].second);
  27.     }
  28.     maxSetup = max(maxSetup, (long long)c[node] + (node ? 0 : sumT)); // node's setup time
  29.     return pair<int, long long>{sumT, maxSetup};
  30. }
  31.  
  32. int main() {
  33.     ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  34.     int n; cin >> n;
  35.     c.resize(n);
  36.     for (int i = 0; i < n; ++i) cin >> c[i];
  37.     g.resize(n);
  38.     for (int i = 1; i < n; ++i) {
  39.         int u, v; cin >> u >> v;
  40.         --u, --v;
  41.         g[u].push_back(v);
  42.         g[v].push_back(u);
  43.     }
  44.     cout << dfs(0).second << endl;
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement