您的位置:首页 > 其它

bzoj2599: [IOI2011]Race

2017-04-23 21:52 267 查看

链接

  http://www.lydsy.com/JudgeOnline/problem.php?id=2599

题解

  这道题题面不清楚,我去查了下原题,发现边权的意义是公里数,也就是说不可能有负数。

  那就可以开一个大小为K的表,table[i]表示到根节点距离为i的点的最小的深度是多少。

  然后就可以点分治,一棵子树一棵子树地往里合并,每次每次要加入一棵子树的时候,就对这棵子树里的每个点查下表,然后更新下答案就好了。

  不知道为什么我那些O(N)数组必须开1.5倍才能A掉,否则就会在第54个测试点WA掉。(查了一晚上就因为这个)

代码

//点分治
#include <cstdio>
#include <algorithm>
#define maxn 300000
#define inf ((long long)1<<60)
#define ll long long
#define forp for(ll p=head[pos];p;p=nex[p])if(to[p]^pre and !grey[to[p]])
using namespace std;
ll N, dist[maxn], deep[maxn], size[maxn], G, sumG, K, ans, head[maxn], to[maxn<<1],
w[maxn<<1], tot, nex[maxn<<1], list[maxn], grey[maxn], table[1000010];
inline void adde(ll a, ll b, ll v)
{to[++tot]=b;w[tot]=v;nex[tot]=head[a];head[a]=tot;}
inline void calc()
{
for(ll i=1;i<=*list;i++)
{
if(dist[list[i]]>K)continue;
ans=min(ans,table[K-dist[list[i]]]+deep[list[i]]);
}
}
inline void ins(ll dist, ll deep)
{
if(dist>K)return;
table[dist]=min(table[dist],deep);
}
ll dfs(ll pos, ll pre)
{
size[pos]=1;
list[++*list]=pos;
forp dist[to[p]]=dist[pos]+w[p], deep[to[p]]=deep[pos]+1,
size[pos]+=dfs(to[p],pos);
return size[pos];
}
void findG(ll pos, ll pre, ll sum)
{
//  printf("%d %d\n",pos,sum);
if(sum<sumG)G=pos, sumG=sum;
forp findG(to[p],pos,sum+*size-size[to[p]]-size[to[p]]);
}
bool solve(ll pos)
{
ll x, i, p;
dist[pos]=deep[pos]=0;
*list=0, dfs(pos,-1);
for(x=0,i=1;i<=*list;i++)x+=deep[list[i]];
*size=size[pos];
G=pos, sumG=x;
findG(pos,-1,x);
grey[G]=1, dist[G]=deep[G]=0;
table[0]=0;
for(p=head[G];p;p=nex[p])
if(!grey[to[p]])
{
*list=0;
dist[to[p]]=w[p], deep[to[p]]=1;
dfs(to[p],-1);
calc();
for(i=1;i<=*list;i++)ins(dist[list[i]],deep[list[i]]);
}
dist[G]=0, dfs(G,-1);
for(i=1;i<=*list;i++)if(dist[list[i]]<=K)table[dist[list[i]]]=inf;
for(p=head[G];p;p=nex[p])if(!grey[to[p]])solve(to[p]);
}
inline ll read(ll x=0)
{
char c=getchar();
bool f=0;
while(c<48 or c>57)f=f|(c=='-'),c=getchar();
while(c>=48 and c<=57)x=(x<<1)+(x<<3)+c-48, c=getchar();
return f?-x:x;
}
void input()
{
ll a, b, v, i;
N=read(), K=read();
for(i=1;i<N;i++)
{
a=read()+1, b=read()+1, v=read();
adde(a,b,v), adde(b,a,v);
}
}
int main()
{
input();
ans=inf;
for(int i=0;i<=K;i++)table[i]=inf;
solve(1);
printf("%lld",ans==inf?-1:ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: