답안 #768772

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
768772 2023-06-28T15:04:16 Z MetalPower Torrent (COI16_torrent) C++14
100 / 100
394 ms 27636 KB
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define pii pair<int, int>
#define fi first
#define se second

const int INF = 1e9 + 7;
const int MX = 3e5 + 10;

int N, A, B; vector<int> nds;
vector<int> adj[MX];

int dfs(int u, int v){
	if(u == B) return 1;
	int val = 0;
	for(int nxt : adj[u]){
		if(nxt == v) continue;
		int curr = dfs(nxt, u);
		if(curr == 1) nds.push_back(nxt), val = 1;
	}
	if(u == A) return 0;
	else return val;
}

void chmax(int& a, int b){
	if(b > a) a = b;
}

int dead_node, dp[MX];

int solve(int u, int v){

	vector<int> vec;
	for(int nxt : adj[u]){
		if(nxt == v || nxt == dead_node) continue;
		solve(nxt, u);
		vec.push_back(dp[nxt]);
	}

	sort(vec.begin(), vec.end(), greater<int>());
	dp[u] = 0;

	for(int i = 0; i < (int) vec.size(); i++) chmax(dp[u], vec[i] + i + 1);
	return dp[u];
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

	cin >> N >> A >> B;
	for(int i = 1; i < N; i++){
		int u, v; cin >> u >> v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	dfs(A, 0); nds.push_back(A);
	reverse(nds.begin(), nds.end());

	int l = 1, r = (int) nds.size() - 1, memo = 0, ans = INF;
	for(; l <= r; ){
		int mid = l + r >> 1;
		dead_node = nds[mid];
		int lf = solve(A, 0);
		dead_node = nds[mid - 1];
		int rg = solve(B, 0);
		if(lf <= rg){
			memo = mid; l = mid + 1;
		}else{
			r = mid - 1;
		}
	}

	if(1 <= memo && memo < (int) nds.size()){
		dead_node = nds[memo];
		int lf = solve(A, 0);
		dead_node = nds[memo - 1];
		int rg = solve(B, 0);
		ans = min(ans, max(lf, rg));
	}

	if(0 <= memo && memo + 1 < (int) nds.size()){
		dead_node = nds[memo + 1];
		int lf = solve(A, 0);
		dead_node = nds[memo];
		int rg = solve(B, 0);
		ans = min(ans, max(lf, rg));
	}

	cout << ans << '\n';
}

Compilation message

torrent.cpp: In function 'int main()':
torrent.cpp:64:15: warning: suggest parentheses around '+' inside '>>' [-Wparentheses]
   64 |   int mid = l + r >> 1;
      |             ~~^~~
# 결과 실행 시간 메모리 Grader output
1 Correct 4 ms 7380 KB Output is correct
2 Correct 4 ms 7380 KB Output is correct
3 Correct 4 ms 7376 KB Output is correct
# 결과 실행 시간 메모리 Grader output
1 Correct 394 ms 24424 KB Output is correct
2 Correct 311 ms 25772 KB Output is correct
3 Correct 375 ms 27240 KB Output is correct
4 Correct 297 ms 26652 KB Output is correct
5 Correct 314 ms 23772 KB Output is correct
6 Correct 301 ms 24468 KB Output is correct
7 Correct 280 ms 27636 KB Output is correct