bzoj2599: [IOI2011]Race

本文介绍了一种使用点分治解决特定类型问题的方法。通过维护一个表来记录到达根节点不同距离的最浅深度,实现对子树的有效合并。特别讨论了如何避免内存溢出等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

  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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值