結果

問題 No.806 木を道に
ユーザー 沙耶花沙耶花
提出日時 2020-11-28 18:05:24
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,780 bytes
コンパイル時間 2,482 ms
コンパイル使用メモリ 214,556 KB
実行使用メモリ 17,880 KB
最終ジャッジ日時 2023-10-10 00:50:10
合計ジャッジ時間 7,675 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,352 KB
testcase_01 AC 1 ms
4,352 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 1 ms
4,352 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 2 ms
4,348 KB
testcase_08 AC 2 ms
4,352 KB
testcase_09 AC 2 ms
4,348 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 42 ms
10,384 KB
testcase_25 AC 62 ms
14,524 KB
testcase_26 AC 22 ms
7,684 KB
testcase_27 AC 71 ms
17,880 KB
testcase_28 AC 3 ms
4,348 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define Inf 1000000000000000000

struct tree_diameter{
	const long long X = 1000000000000000000;
	pair<long long,vector<int>> get(vector<vector<pair<int,long long>>> &E){
		vector<long long> dis = bfs(E,0);
		long long maxi = -1;
		int ind = 0;
		for(int i=0;i<E.size();i++){
			if(dis[i]>maxi){
				maxi=dis[i];
				ind=i;
			}
		}

		dis = bfs(E,ind);
		maxi = -1;

		for(int i=0;i<E.size();i++){
			if(dis[i]>maxi){
				maxi=dis[i];
				ind=i;
			}
		}

		vector<int> ret;
		ret.push_back(ind);
		while(dis[ind]!=0LL){
			for(int i=0;i<E[ind].size();i++){
				if(dis[ind] == dis[E[ind][i].first] + E[ind][i].second){
					ind = E[ind][i].first;
					ret.push_back(ind);
					break;
				}
			}
		}
		
		return make_pair(maxi,ret);
		
	}
	
	pair<long long,vector<int>> get(vector<vector<int>> &E){
		vector<vector<pair<int,long long>>> e(E.size(),vector<pair<int,long long>>());
		for(int i=0;i<E.size();i++){
			for(int j=0;j<E[i].size();j++){
				e[i].emplace_back(E[i][j],1LL);
			}
		}
		return get(e);
	}
	
	vector<long long> bfs(vector<vector<pair<int,long long>>> &E,int start){
		vector<long long> dis(E.size(),X);
		dis[start] = 0LL;
		queue<int> Q;
		Q.push(start);
		
		while(Q.size()!=0){
			int u = Q.front();
			Q.pop();
			for(int i=0;i<E[u].size();i++){
				int v = E[u][i].first;
				if(dis[v]!=X)continue;
				dis[v] = dis[u] + E[u][i].second;
				Q.push(v);
			}
		}
		return dis;
	}
	
};

int main(){
	
	int N;
	cin>>N;
	
	vector<vector<int>> E(N,vector<int>());
	
	rep(i,N-1){
		int a,b;
		cin>>a>>b;
		a--;b--;
		E[a].push_back(b);
		E[b].push_back(a);
	}
	
	tree_diameter T;
	
	int x = T.get(E).first;
	
	cout<<N-1-x<<endl;
	
	
    return 0;
}
0