結果

問題 No.806 木を道に
ユーザー CleyLCleyL
提出日時 2022-05-02 18:14:01
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,652 bytes
コンパイル時間 788 ms
コンパイル使用メモリ 81,624 KB
実行使用メモリ 16,812 KB
最終ジャッジ日時 2023-09-14 14:56:36
合計ジャッジ時間 4,933 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 1 ms
4,376 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 47 ms
12,060 KB
testcase_25 AC 71 ms
16,812 KB
testcase_26 AC 23 ms
6,800 KB
testcase_27 AC 76 ms
15,360 KB
testcase_28 AC 3 ms
4,380 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 = 1; A.path.size()-1 > i; i++){
    ans += B[A.path[i]].size()-2;
  }
  cout << ans << endl;
}
0