Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4149 [IOI2011]Race

P4149 [IOI2011]Race

点分治后暴力即可。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <cstdio>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (flag) x = ~x + 1;
}
template <class Type, class ...rest>
void read(Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write(Type x)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
void chkmax (int &x, int k) { if (k > x) x = k; }
void chkmin (int &x, int k) { if (k < x) x = k; }
const int N = 2e5 + 10, M = 4e5 + 10, K = 1e6 + 10;
bool vis[N];
int n, m, ans, f[K];
int idx, hd[N], nxt[M], edg[M], wt[M];
void add (int a, int b, int c)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
wt[idx] = c;
}
int Size (int x, int fa)
{
if (vis[x]) return 0;
int res = 1;
for (int i = hd[x]; i; i = nxt[i])
if (edg[i] ^ fa) res += Size(edg[i], x);
return res;
}
int WeightCentre (int x, int fa, int tot, int &wc)
{
if (vis[x]) return 0;
int sum = 1, mx = 0;
for (int i = hd[x]; i; i = nxt[i])
if (edg[i] ^ fa)
{
int t = WeightCentre(edg[i], x, tot, wc);
chkmax(mx, t), sum += t;
}
chkmax(mx, tot - sum);
if (mx <= tot / 2) wc = x;
return sum;
}
void Query (int x, int fa, int s, int t)
{
if (vis[x] || s > m || t > ans) return;
chkmin(ans, f[m - s] + t);
for (int i = hd[x]; i; i = nxt[i])
if (edg[i] ^ fa) Query(edg[i], x, s + wt[i], t + 1);
}
void Modify (int x, int fa, int s, int t)
{
if (vis[x] || s > m || t > ans) return;
chkmin(f[s], t);
for (int i = hd[x]; i; i = nxt[i])
if (edg[i] ^ fa) Modify(edg[i], x, s + wt[i], t + 1);
}
void Init (int x, int fa, int s, int t)
{
if (vis[x] || s > m || t > ans) return;
f[s] = n;
for (int i = hd[x]; i; i = nxt[i])
if (edg[i] ^ fa) Init(edg[i], x, s + wt[i], t);
}
void calc (int x)
{
if (vis[x]) return;
WeightCentre(x, -1, Size(x, -1), x);
vis[x] = true;
for (int i = hd[x]; i; i = nxt[i])
Query(edg[i], x, wt[i], 1), Modify(edg[i], x, wt[i], 1);
for (int i = hd[x]; i; i = nxt[i])
Init(edg[i], x, wt[i], 1);
for (int i = hd[x]; i; i = nxt[i])
calc(edg[i]);
}
int main ()
{
read(n, m);
for (int i = 1; i <= m; ++i) f[i] = n;
for (int i = 1, a, b, c; i < n; ++i)
{
read(a, b, c); ++a, ++b;
add(a, b, c), add(b, a, c);
}
ans = n;
calc(1);
write(ans == n ? -1 : ans);
return 0;
}