2599: [IOI2011]Race
Time Limit: 70 Sec Memory Limit: 128 MBSubmit: 3213 Solved: 943
[ Submit][ Status][ Discuss]
Description
给一棵树,每条边有权.求一条简单路径,权值和等于K,且边的数量最小.N <= 200000, K <= 1000000
Input
第一行 两个整数 n, k
第二..n行 每行三个整数 表示一条无向边的两端和权值 (注意点的编号从0开始)
Output
一个整数 表示最小边数量 如果不存在这样的路径 输出-1
Sample Input
4 3
0 1 1
1 2 2
1 3 4
0 1 1
1 2 2
1 3 4
Sample Output
2
HINT
Source
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<vector>
using namespace std;
const int maxn = 2E5 + 20;
struct E{
int to,w; E(){}
E(int to,int w): to(to),w(w){}
};
struct Node{
Node *ch[2];
int siz,key,w;
}*rt,*tot,pool[maxn];
int n,m,Ans,cnt,Max,O,siz[maxn];
bool Huge[maxn];
vector <E> v[maxn];
int getint()
{
char ch = getchar(); int ret = 0;
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9')
ret = ret * 10 + ch - '0',ch = getchar();
return ret;
}
void Dfs1(int x,int fa,int tot)
{
int ma = 0; siz[x] = 1;
for (int i = 0; i < v[x].size(); i++)
{
int to = v[x][i].to;
if (to == fa || Huge[to]) continue;
Dfs1(to,x,tot); siz[x] += siz[to]; ma = max(ma,siz[to]);
}
ma = max(ma,tot - siz[x]);
if (ma < Max) Max = ma,O = x;
}
int cmp(Node *&x,int key)
{
if (x->key == key) return -1;
return x->key > key ? 0 : 1;
}
void rotate(Node *&x,int d)
{
Node *y = x->ch[d];
x->ch[d] = y->ch[d^1];
y->ch[d^1] = x; x = y;
}
void Insert(Node *&x,int siz,int key,int w)
{
if (x == NULL)
{
x = &pool[++cnt];
x->siz = siz; x->key = key; x->w = w;
x->ch[0] = x->ch[1] = NULL; return;
}
int d = cmp(x,key);
if (d == -1) {x->siz = min(x->siz,siz); return;}
Insert(x->ch[d],siz,key,w); if (x->ch[d]->w > x->w) rotate(x,d);
}
int Query(Node *x,int key)
{
if (x == NULL) return maxn;
int d = cmp(x,key);
return d == -1 ? x->siz : Query(x->ch[d],key);
}
void Dfs2(int x,int fa,int sum,int siz)
{
if (sum >= m)
{
if (sum == m) Ans = min(Ans,siz);
return;
}
int ret = Query(rt,m - sum);
Ans = min(Ans,siz + ret);
for (int i = 0; i < v[x].size(); i++)
{
E e = v[x][i];
if (e.to == fa || Huge[e.to]) continue;
Dfs2(e.to,x,sum + e.w,siz + 1);
}
}
void Dfs3(int x,int fa,int sum,int siz)
{
if (sum >= m) return;
Insert(rt,siz,sum,rand());
for (int i = 0; i < v[x].size(); i++)
{
E e = v[x][i];
if (e.to == fa || Huge[e.to]) continue;
Dfs3(e.to,x,sum + e.w,siz + 1);
}
}
void Solve(int x,int tot)
{
Max = maxn; Dfs1(x,-1,tot); rt = NULL;
int o = O; Huge[o] = 1; cnt = 0;
for (int i = 0; i < v[o].size(); i++)
{
E e = v[o][i];
if (Huge[e.to]) continue;
Dfs2(e.to,o,e.w,1); Dfs3(e.to,o,e.w,1);
}
for (int i = 0; i < v[o].size(); i++)
{
E e = v[o][i];
if (Huge[e.to]) continue;
Solve(e.to,siz[e.to]);
}
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
n = Ans = getint(); m = getint();
for (int i = 1; i < n; i++)
{
int x = getint() + 1,y,w;
y = getint() + 1; w = getint();
v[x].push_back(E(y,w));
v[y].push_back(E(x,w));
}
Solve(1,n);
cout << (Ans == n ? -1 : Ans) << endl;
return 0;
}