結果

問題 No.399 動的な領主
ユーザー ikdikd
提出日時 2018-02-12 16:04:56
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 264 ms / 2,000 ms
コード長 1,712 bytes
コンパイル時間 599 ms
コンパイル使用メモリ 85,512 KB
実行使用メモリ 52,252 KB
最終ジャッジ日時 2023-09-03 18:45:01
合計ジャッジ時間 5,484 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 3 ms
4,380 KB
testcase_05 AC 20 ms
8,476 KB
testcase_06 AC 264 ms
42,904 KB
testcase_07 AC 253 ms
42,960 KB
testcase_08 AC 248 ms
42,924 KB
testcase_09 AC 246 ms
42,840 KB
testcase_10 AC 3 ms
4,376 KB
testcase_11 AC 20 ms
8,028 KB
testcase_12 AC 217 ms
42,776 KB
testcase_13 AC 221 ms
42,996 KB
testcase_14 AC 181 ms
50,640 KB
testcase_15 AC 191 ms
52,252 KB
testcase_16 AC 203 ms
46,608 KB
testcase_17 AC 241 ms
43,012 KB
testcase_18 AC 251 ms
42,960 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class Tree{
  import std.algorithm;
  int[][] g;
  int[][] par;
  int[] dep;
  int n;
  const int len=17; // n <= 1e5
  long[] sub;
  this(int n){
    this.n=n;
    g.length=n;
    par=new int[][](n, len);
    foreach(i; 0..n) fill(par[i], -1);
    dep.length=n;
    sub.length=n;
  }
  void addEdge(int u, int v){
    g[u]~=v; g[v]~=u;
  }
  void dfs(int i=0, int j=-1){
    par[i][0]=j;
    if(j>=0) dep[i]=dep[j]+1;
    foreach(k; g[i]){
      if(j!=k) dfs(k, i); 
    }
  }
  void init(){
    dfs();
    for(int j=0; j<len-1; j++)foreach(i; 0..n){
      if(par[i][j]>=0) par[i][j+1]=par[par[i][j]][j];
    }
  }
  int getLca(int s, int t){
    if(dep[s]<dep[t]) swap(s, t);
    foreach(i; 0..len){
      if((dep[s]-dep[t])&(1<<i)) s=par[s][i];
    }
    if(s==t) return s;
    for(auto i=len-1; i>=0; i--){
      if(par[s][i]!=par[t][i]) s=par[s][i], t=par[t][i];
    }
    return par[s][0];
  }
  void set(int s, int t){
    sub[s]++; sub[t]++;
    auto lca=getLca(s, t);
    sub[lca]--;
    if(lca>0) sub[par[lca][0]]--;
  }
  void add(int i=0, int p=-1){
    foreach(j; g[i])if(j!=p){
      add(j, i);
      sub[i]+=sub[j];
    }
  }
  long acc(){
    return reduce!((r,e)=>(r+e*(e+1)/2))(0L, sub);
  }
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; rd(n);
  auto tree=new Tree(n);
  foreach(_; 0..(n-1)){
    int u, v; rd(u, v);
    tree.addEdge(u-1, v-1);
  }
  tree.init;
  int q; rd(q);
  while(q--){
    int u, v; rd(u, v);
    tree.set(u-1, v-1);
  }

  tree.add;
  writeln(tree.acc);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}
0