結果

問題 No.806 木を道に
ユーザー CleyLCleyL
提出日時 2022-05-02 18:33:21
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 148 ms / 2,000 ms
コード長 1,642 bytes
コンパイル時間 895 ms
コンパイル使用メモリ 82,712 KB
実行使用メモリ 16,776 KB
最終ジャッジ日時 2023-09-14 15:21:06
合計ジャッジ時間 3,932 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 1 ms
4,380 KB
testcase_09 AC 2 ms
4,376 KB
testcase_10 AC 24 ms
5,804 KB
testcase_11 AC 21 ms
5,352 KB
testcase_12 AC 118 ms
13,052 KB
testcase_13 AC 78 ms
10,472 KB
testcase_14 AC 109 ms
12,660 KB
testcase_15 AC 115 ms
13,364 KB
testcase_16 AC 40 ms
6,776 KB
testcase_17 AC 98 ms
11,812 KB
testcase_18 AC 9 ms
4,380 KB
testcase_19 AC 26 ms
5,716 KB
testcase_20 AC 102 ms
11,896 KB
testcase_21 AC 53 ms
8,032 KB
testcase_22 AC 148 ms
15,000 KB
testcase_23 AC 144 ms
15,064 KB
testcase_24 AC 47 ms
12,228 KB
testcase_25 AC 74 ms
16,776 KB
testcase_26 AC 23 ms
6,800 KB
testcase_27 AC 75 ms
15,308 KB
testcase_28 AC 3 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
using namespace std;
template<typename T>
struct TreeDiameter{
  struct edge{
    int to;
    T cost;
  };
  int n;
  T generated;
  vector<vector<edge>> tree; 
  vector<int> path;
  vector<int> C;
  
  TreeDiameter(int n_) : n(n_),tree(n_) {
    generated = -1;
  }

  void add(int s,int v){
    tree[s].push_back({v,1});
    tree[v].push_back({s,1});
    generated = -1;
  }

  void add(int s,int v,T c){
    tree[s].push_back({v,c});
    tree[v].push_back({s,c});
    generated = -1;
  }

  T build(){
    if(generated != -1)return generated;
    auto x = DFS(0);
    auto y = DFS(x.first);
    int nw = x.first;
    while(y.first != nw){
      path.push_back(nw);
      nw = C[nw];
    }
    path.push_back(nw);
    return generated = y.second;
  }

private:
  //DFS(int, T, (int)) -> pair<int,int>
  pair<int,T> DFS(int nw,T dist=0,int initnal=1){
    if(initnal){
      C.assign(n,-1);
      path.clear();
      initnal = 0;
    }
    C[nw] = 0;
    pair<int,T> ret = make_pair(nw,dist);
    for(int i = 0; tree[nw].size() > i; i++){
      if(C[tree[nw][i].to] == -1){
        pair<int,T> x = DFS(tree[nw][i].to,dist+tree[nw][i].cost,0);
        if(ret.second < x.second){
          ret = x;
          C[nw] = tree[nw][i].to;
        }
      }
    }
    return ret;
  }
};


int main(){
  int n;cin>>n;
  TreeDiameter<int> A(n);
  vector<int> B[n];
  for(int i = 0; n-1 > i; i++){
    int s,v;cin>>s>>v;
    A.add(--s,--v);
    B[s].push_back(v);
    B[v].push_back(s);
  }
  A.build();
  int ans = 0;
  for(int i = 0; n > i; i++){
    ans += max(0,(int)B[i].size()-2);
  }
  cout << ans << endl;
}
0