답안 #104918

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
104918 2019-04-09T17:24:46 Z Shtef Torrent (COI16_torrent) C++14
100 / 100
1281 ms 33796 KB
#include <iostream>
#include <utility>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;
#define x first
#define y second
#define mp make_pair

int n, tx, ty, dth[300005];
vector <pii> ms[300005];
bool bio[300005];
vector <int> naputu;
pii par[300005];
const ll inf = (ll)1e15;

bool cmp(ll x, ll y){
	return x > y;
}

void dfs1(int x, int p){
	for(vector <pii>::iterator i = ms[x].begin() ; i != ms[x].end() ; ++i){
		pii o = *i;
		if(o.x == p || bio[o.y])
			continue;
		par[o.x] = mp(x, o.y);
		dth[o.x] = dth[x] + 1;
		dfs1(o.x, x);
	}
}

ll dfs2(int x, int p){
	ll ret = 0;
	vector <ll> v;
	for(vector <pii>::iterator i = ms[x].begin() ; i != ms[x].end() ; ++i){
		pii o = *i;
		if(o.x == p || bio[o.y])
			continue;
		v.push_back(dfs2(o.x, x));
	}
	sort(v.begin(), v.end(), cmp);
	for(int i = 0 ; i < (int)v.size() ; ++i){
		ret = max(ret, v[i] + i + 1);
	}
	return ret;
}

void odigore(int &x, int k, vector <int> &v){
	for(int i = 0 ; i < k ; ++i){
		v.push_back(par[x].y);
		x = par[x].x;
	}
}

void nadiput(int x, int y){
	vector <int> prvi, drugi;
	if(dth[x] > dth[y]){
		odigore(x, dth[x] - dth[y], prvi);
	}
	else if(dth[y] > dth[x]){
		odigore(y, dth[y] - dth[x], drugi);
	}
	while(x != y){
		prvi.push_back(par[x].y);
		x = par[x].x;
		drugi.push_back(par[y].y);
		y = par[y].x;
	}
	for(int i = 0 ; i < (int)prvi.size() ; ++i){
		naputu.push_back(prvi[i]);
	}
	for(int i = (int)drugi.size() - 1 ; i >= 0 ; --i){
		naputu.push_back(drugi[i]);
	}
}

int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> tx >> ty;
for(int i = 0 ; i < n - 1 ; ++i){
	int x, y;
	cin >> x >> y;
	ms[x].push_back(mp(y, i));
	ms[y].push_back(mp(x, i));
}
dfs1(1, -1);
nadiput(tx, ty);
int l = 0, r = (int)naputu.size() - 1;
ll sol = inf;
while(l < r){
	int mid = (l + r) / 2;
	bio[naputu[mid]] = 1;
	if(dfs2(tx, -1) < dfs2(ty, -1)){
		l = mid + 1;
	}
	else{
		r = mid;
	}
	sol = min(sol, max(dfs2(tx, -1), dfs2(ty, -1)));
	bio[naputu[mid]] = 0;
}
bio[l] = 1;
sol = min(sol, max(dfs2(tx, -1), dfs2(ty, -1)));
cout << sol << endl;

return 0;
}
# 결과 실행 시간 메모리 Grader output
1 Correct 10 ms 7424 KB Output is correct
2 Correct 11 ms 7552 KB Output is correct
3 Correct 9 ms 7424 KB Output is correct
# 결과 실행 시간 메모리 Grader output
1 Correct 1238 ms 29560 KB Output is correct
2 Correct 1224 ms 31604 KB Output is correct
3 Correct 1281 ms 32176 KB Output is correct
4 Correct 1154 ms 33504 KB Output is correct
5 Correct 1144 ms 28940 KB Output is correct
6 Correct 1138 ms 29576 KB Output is correct
7 Correct 934 ms 33796 KB Output is correct