Advertisement
erek1e

POI Task Barricades

Jul 1st, 2023
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. const int INF = 1e5;
  8.  
  9. vector<vector<int>> g;
  10. vector<vector<int>> costs;
  11. /* for each node i, cost[i][k] is the minimum subtree edges that need to
  12. be blocked to turn the subtree with root node i into a component of size k*/
  13. void findCosts(int node = 1, int parent = 0) {
  14.     costs[node] = {!!parent, 0};
  15.     for (int child : g[node]) {
  16.         if (child == parent) continue;
  17.         findCosts(child, node);
  18.         int a = (int)costs[node].size()-1, b = (int)costs[child].size()-1;
  19.         // operations: a*b, result: a+=b
  20.         vector<int> newCost(1+a+b, INF);
  21.         newCost[0] = !!parent;
  22.         for (int i = 1; i <= a; ++i) {
  23.             for (int j = 0; j <= b; ++j) {
  24.                 newCost[i+j] = min(newCost[i+j], costs[node][i] + costs[child][j]);
  25.             }
  26.         }
  27.         costs[node] = newCost;
  28.     }
  29. }
  30.  
  31. int main() {
  32.     ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  33.     int n; cin >> n;
  34.     g.resize(1+n);
  35.     for (int i = 1; i < n; ++i) {
  36.         int u, v; cin >> u >> v;
  37.         g[u].push_back(v);
  38.         g[v].push_back(u);
  39.     }
  40.  
  41.     costs.resize(1+n);
  42.     findCosts();
  43.     vector<int> minCost(1+n, INF); // to make a component of this size
  44.     for (int i = 1; i <= n; ++i) {
  45.         for (size_t k = 1; k < costs[i].size(); ++k) minCost[k] = min(minCost[k], costs[i][k] + (i != 1));
  46.     }
  47.  
  48.     int m; cin >> m;
  49.     while (m--) {
  50.         int k; cin >> k;
  51.         cout << minCost[k] << '\n'; // never impossible
  52.     }
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement