Official

H - Cut and Add Editorial by en_translator Editorial for printing


Regard the tree rooted at vertex \(1\).
Let \(seq\) be the sequence of the vertices visited in a BFS starting from vertex \(1\).

During the first BFS, we can find for each vertex its parent and the edge index that leads to that parent.

For each edge, the sizes of the two connected component obtained by removing that edge can be computed, in reverse order of \(seq\), as the size of the subtree rooted at each vertex.

Now we will perform the additions requested in the problem statement. Here, notice that additions may be done in any order (the edges can be processed in any order).

Suppose that edge \(i\) is incident to vertex \(v\) toward the root.
If the subtree of \(v\) has a size greater than \(n/2\), then we add \(i\) to all vertices in the subtree under \(v\).
If the subtree of \(v\) has a size less than \(n/2\), the operation can still be treated as an “addition to all vertices in a subtree.” Specifically, promise that we will add \(i\) to all vertices afterward, and add \(-i\) to all vertices in the subtree under \(v\).

Adding a value to all vertices in a subtree can be done by adding that value to the vertex, and then propagating the addition toward leaves by scanning \(seq\) from the beginning.

This solution runs in a total of \(O(N)\) time.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;
using ll=long long;
using pi=pair<int,int>;
using Graph=vector<vector<pi>>;

int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  cin >> n;
  Graph g(n);
  for(int i=1;i<n;i++){
    int a,b;
    cin >> a >> b;
    a--; b--;
    g[a].push_back({b,i});
    g[b].push_back({a,i});
  }
  vector<int> seq;
  vector<int> par(n,-1);
  vector<int> peg(n);
  {
    queue<int> q;
    par[0]=-2;
    peg[0]=0;
    q.push(0);
    while(!q.empty()){
      auto od=q.front(); q.pop();
      seq.push_back(od);
      for(auto &nx : g[od]){
        if(par[nx.first]==-1){
          par[nx.first]=od;
          peg[nx.first]=nx.second;
          q.push(nx.first);
        }
      }
    }
  }

  reverse(seq.begin(),seq.end());
  vector<int> sz(n,1);
  vector<ll> x(n,0);
  ll glob=0;
  for(auto &nx : seq){
    for(auto &ny : g[nx]){
      if(ny.first==par[nx]){continue;}
      sz[nx]+=sz[ny.first];
    }
    if(2*sz[nx]<n){
      glob+=peg[nx];
      x[nx]-=peg[nx];
    }
    else{
      x[nx]+=peg[nx];
    }
  }

  reverse(seq.begin(),seq.end());
  for(auto &nx : seq){
    for(auto &ny : g[nx]){
      if(ny.first==par[nx]){continue;}
      x[ny.first]+=x[nx];
    }
  }

  for(int i=0;i<n;i++){
    if(i){cout << " ";}
    cout << glob+x[i];
  }cout << "\n";
  return 0;
}

Original proposer: admin

posted:
last update: