Submission #43652

#TimeUsernameProblemLanguageResultExecution timeMemory
43652baactreeRace (IOI11_race)C++14
100 / 100
1544 ms43684 KiB
#include "race.h"
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int n, k;
vector<pair<int, int> > adj[200005];
int cnt[200005], trip[200005];
int get_cnt(int now, int par) {
	cnt[now] = 1;
	for (auto &there : adj[now]) {
		if (there.first == par || trip[there.first])continue;
		cnt[now] += get_cnt(there.first, now);
	}
	return cnt[now];
}
int get_centroid(int now, int par,int c) {
	for (auto &there : adj[now]) {
		if (there.first == par || trip[there.first])continue;
		if(cnt[there.first]>c)
			return get_centroid(there.first, now, c);
	}
	return now;
}
void dfs(int now, int par, int weight, int depth, vector<pair<int, int> > &vec) {
	vec.emplace_back(weight, depth);
	for (auto &there : adj[now]) {
		if (there.first == par || trip[there.first])continue;
		dfs(there.first, now, weight + there.second, depth + 1, vec);
	}
}
int solve(int now) {
	get_cnt(now, -1);
	int centroid = get_centroid(now, -1, cnt[now] / 2);
	trip[centroid] = true;
	int ret = inf;
	map<int, int> mp;
	mp[0] = 0;
	for (auto &there : adj[centroid]) {
		if (trip[there.first])continue;
		vector<pair<int, int> > vec;
		dfs(there.first, centroid, there.second, 1, vec);
		for (auto x : vec) 
			if (mp.count(k - x.first)) 
				ret = min(ret, x.second + mp[k - x.first]);
		for (auto x : vec) {
			if (!mp.count(x.first))
				mp[x.first] = x.second;
			else
				mp[x.first] = min(mp[x.first], x.second);
		}
	}
	for (auto &there : adj[centroid]) {
		if (trip[there.first])continue;
		ret = min(ret, solve(there.first));
	}
	return ret;
}
int best_path(int N, int K, int H[][2], int L[])
{
	n = N; k = K;
	for (int i = 0; i < n - 1; i++) {
		adj[H[i][0]].emplace_back(H[i][1], L[i]);
		adj[H[i][1]].emplace_back(H[i][0], L[i]);
	}
	int ret = solve(0);
	return ret == inf ? -1 : ret;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...