Submission #104919

# Submission time Handle Problem Language Result Execution time Memory
104919 2019-04-09T17:28:34 Z Shtef Torrent (COI16_torrent) C++14
100 / 100
704 ms 29472 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;
	ll x = dfs2(tx, -1);
	ll y = dfs2(ty, -1);
	if(x < y){
		l = mid + 1;
	}
	else{
		r = mid;
	}
	sol = min(sol, max(x, y));
	bio[naputu[mid]] = 0;
}
bio[l] = 1;
sol = min(sol, max(dfs2(tx, -1), dfs2(ty, -1)));
cout << sol << endl;

return 0;
}
# Verdict Execution time Memory Grader output
1 Correct 10 ms 7424 KB Output is correct
2 Correct 9 ms 7552 KB Output is correct
3 Correct 9 ms 7552 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 704 ms 25388 KB Output is correct
2 Correct 695 ms 27688 KB Output is correct
3 Correct 688 ms 27956 KB Output is correct
4 Correct 613 ms 29328 KB Output is correct
5 Correct 644 ms 24828 KB Output is correct
6 Correct 669 ms 25452 KB Output is correct
7 Correct 602 ms 29472 KB Output is correct