# Algorithm Analyse

$dist[i]+dist[j] = K\ and\ Belong[i] \neq Belong[j]$

# Code

//[bzoj2599][IOI2011]Race
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
#include <vector>
#ifndef ONLINE_JUDGE
const int maxn = 200;
#else
const int maxn = 200050;
#endif
using std::max;
using std::vector;
using std::min;
int n, m, k, rt, ans, sum;
int tot = 0, deep[maxn], dep[maxn], vis[maxn], size[maxn], f[maxn], t[1000005];
struct edge {
int to, v;
};
vector<edge> G[maxn];
void add_edge(int u, int v, int w) {
G[u].push_back((edge){v, w});
G[v].push_back((edge){u, w});
}
void getroot(int x, int fa) {
size[x] = 1;
f[x] = 0;
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to] && e.to != fa) {
getroot(e.to, x);
size[x] += size[e.to];
f[x] = max(f[x], size[e.to]);
}
}
f[x] = max(f[x], sum - size[x]);
if (f[x] < f[rt])
rt = x;
}
void getdeep(int x, int fa) {
if (deep[x] <= k)
ans = min(ans, dep[x] + t[k - deep[x]]);
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to] && e.to != fa) {
dep[e.to] = dep[x] + 1;
deep[e.to] = deep[x] + e.v;
getdeep(e.to, x);
}
}
}
void update(int x, int fa, bool flag) {
if (deep[x] <= k) {
if (flag)
t[deep[x]] = min(t[deep[x]], dep[x]);
else
t[deep[x]] = 0x3f3f3f;
}
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to] && e.to != fa)
update(e.to, x, flag);
}
}
void work(int x) {
vis[x] = 1;
t[0] = 0;
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to]) {
dep[e.to] = 1;
deep[e.to] = e.v;
getdeep(e.to, 0);
update(e.to, 0, 1);
}
}
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to])
update(e.to, 0, 0);
}
for (int i = 0; i < G[x].size(); i++) {
edge &e = G[x][i];
if (!vis[e.to]) {
rt = 0;
sum = size[e.to];
getroot(e.to, 0);
work(rt);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input", "r", stdin);
#endif
scanf("%d %d", &n, &k);
for (int i = 1; i < n; i++) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
x++, y++;
}
f[0] = sum = ans = n;
memset(t, 0x3f, sizeof(t));
getroot(1, 0);
work(rt);
printf("%d\n", ans == n ? -1 : ans);
}

posted on 2017-03-05 16:44  蒟蒻konjac  阅读(...)  评论(... 编辑 收藏

• 随笔 - 168
• 文章 - 0
• 评论 - 32