結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー ocvret_
提出日時 2021-03-05 22:18:46
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 165 ms / 2,000 ms
コード長 1,983 bytes
コンパイル時間 1,749 ms
コンパイル使用メモリ 177,404 KB
実行使用メモリ 48,128 KB
最終ジャッジ日時 2024-10-07 02:34:53
合計ジャッジ時間 5,318 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
// #include<atcoder/all>
// #include<boost/multiprecision/cpp_int.hpp>

using namespace std;
// using namespace atcoder;
// using bint = boost::multiprecision::cpp_int;
using ll = long long;
using ull = unsigned long long;
using P = pair<int,int>;
#define rep(i,n) for(ll i = 0;i < (ll)n;i++)
#define ALL(x) (x).begin(),(x).end()
#define MOD 1000000007


// 2020/12/31

struct Rerooting{
  struct DP{
    /*
      add variables ,edit constructer and functions
    */
    ll s = 0,x = 0;
    DP(){}
    DP operator+(const DP& o){
      DP res;
      res.x = this->x + o.x;
      res.s = this->s + o.s;
      return res;
    }
    DP addRoot()const{
      DP res(*this);
      res.x++;
      res.s += res.x;
      return res;
    }
  };
  vector<vector<int>> v;
  vector<vector<DP>> dp;
  vector<DP> res;
  Rerooting(int n = 0) : v(n),dp(n),res(n) {}
  void add_edge(int a,int b){
    v[a].push_back(b);
    v[b].push_back(a);
  }
  void init(){
    dfs(0);
    bfs(0);
  }
  DP dfs(int ov,int pre = -1){
    DP S;
    int deg = v[ov].size();
    dp[ov] = vector<DP>(deg);
    for(int i = 0;i < deg;i++){
      int nv = v[ov][i];
      if(nv == pre)continue;
      dp[ov][i] = dfs(nv,ov);
      S = S + dp[ov][i];
    }
    return S.addRoot();
  }
  void bfs(int ov,const DP &dp_pre = DP(),int pre = -1){
    int deg = v[ov].size();
    vector<DP> L(deg+1),R(deg+1);
    for(int i = 0;i < deg;i++)if(v[ov][i] == pre)dp[ov][i] = dp_pre;
    for(int i = 0;i < deg;i++)L[i+1] = L[i] + dp[ov][i];
    for(int i = deg-1;i >= 0;i--)R[i] = R[i+1] + dp[ov][i];
    res[ov] = L[deg].addRoot();
    for(int i = 0;i < deg;i++){
      int nv = v[ov][i];
      if(nv == pre)continue;
      bfs(nv,(L[i] + R[i+1]).addRoot(),ov);
    }
  }
};

int main(){
  
  int n;
  cin >> n;
  Rerooting rt(n);
  rep(i,n-1){
    int a,b;cin >> a >> b;
    a--;b--;
    rt.add_edge(a,b);
  }
  rt.init();
  ll res = 0;
  rep(i,n)res += rt.res[i].s;
  cout << res << "\n";
  

  return 0;
}
0