您的位置:首页 > 其它

Codevs 2756 树上的路径

2016-12-13 22:04 381 查看

2756 树上的路径

时间限制: 3 s     空间限制: 128000 KB     题目等级 : 大师 Master

题目描述 Description

给出一棵树,求出最小的k,使得,且在树中存在路径P,使得k>= S 且 k <=E. (k为路径P上的边的权值和)

输入描述 Input Description

第一行给出N,S,E,N代表树的点数,S,E如题目描述一致

下面N-1行给出这棵树的相邻两个节点的边及其权值W

输出描述 Output Description

输出一个整数k,表示存在路径P,并且路径上的权值和 K>=S , k<=E,若无解输出-1

样例输入 Sample Input

5 10 40

2 4 80

2 3 57

1 2 16

2 5 49

样例输出 Sample Output

16

数据范围及提示 Data Size & Hint

边权W<=10000,

保证答案在int(longint)范围内,且|E-S|<=50,

树上点的个数N<=30000

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 30009
using namespace std;
int n,A,B,K,la,head
,next[N<<1],ans=2*1e9,size
;
int dep
,maxson
,root,tot,lls,num,ls
;
bool v
;
struct node
{
int fr,to,len;
}a[N<<1];
void addedge(int x,int y,int z)
{
a[++la].fr=x,a[la].to=y,a[la].len=z;
next[la]=head[x],head[x]=la;
}
void get_root(int x,int from)
{
size[x]=1;
maxson[x]=0;
for(int i=head[x];i;i=next[i])
if (!v[ a[i].to ]&&a[i].to!=from)
{
get_root(a[i].to,x);
size[x]+=size[ a[i].to ];
maxson[x]=max(maxson[x],size[ a[i].to ]);
}
maxson[x]=max( maxson[x],tot-size[x] );
if (!root||maxson[x]<maxson[root]) root=x;

}
void get_dep(int x,int from)
{
for (int i=head[x];i;i=next[i])
if (!v[ a[i].to ]&&a[i].to!=from)
{
ls[++lls]=dep[ a[i].to ]=dep[x]+a[i].len;
get_dep(a[i].to,x);

}
}
int get_num(int x,int jian)
{
int i,j,k,rt=0;
ls[ lls=1 ]=dep[x]=jian;
get_dep(x,0);

sort(ls+1,ls+lls+1);
for (i=1,j=lls;i<=lls;i++)
{
while (j>1&&ls[i]+ls[j]>K) j--;
if (j>i)rt+=j-i;
}
return rt;
}
void divide(int x)
{
num+=get_num(x,0);
v[x]=1;
for (int i=head[x];i;i=next[i])
if (!v[ a[i].to ])
{
num-=get_num(a[i].to,a[i].len);
tot=size[ a[i].to ];
root=0,get_root(a[i].to,0);
divide( root );
}
}
int main()
{
int i,j,k,x,y,z,last;
scanf("%d%d%d",&n,&A,&B);
for(i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z),addedge(y,x,z);
}
last=1e9;
for(K=A-1;K<=B;K++)
{
num=0;
memset(v,0,sizeof(v));
tot=n,root=0;
get_root(1,0);
divide(root);
if(num>last)
{
printf("%d\n",K);
return 0;
}
last=num;
}
printf("-1\n");
}


备注:引用自Codevs 题解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: