3365: [Usaco2004 Feb]Distance Statistics 路程统计|树的点分治

本文详细介绍了一种基于图论的算法实现,包括数据结构定义、核心算法流程及具体操作步骤。通过递归分解树状结构,利用双端队列进行节点间距离计算,实现了高效的路径搜索与分析。

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

双倍经验QAQ http://blog.youkuaiyun.com/ws_yzy/article/details/50876079

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
#define N 80022
using namespace std;
int sc()
{
    int i=0,f=1; char c=getchar();
    while(c>'9'||c<'0'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9')i=i*10+c-'0',c=getchar();
    return i*f;
}
int vis[N],mx[N],size[N],a[N],dis[N];
int head[N],nxt[N],lst[N],v[N];
int m,tot,n,K,sum,root,ans,top,TI;
void insert(int x,int y,int z)
{
    lst[++tot]=y;nxt[tot]=head[x];head[x]=tot;v[tot]=z;
    lst[++tot]=x;nxt[tot]=head[y];head[y]=tot;v[tot]=z;
}
void get_root(int x,int f)
{
    size[x]=1;mx[x]=0;
    for(int i=head[x];i;i=nxt[i])
        if(lst[i]!=f&&!vis[lst[i]])
        {
            get_root(lst[i],x);
            size[x]+=size[lst[i]];
            mx[x]=max(mx[x],size[lst[i]]);
        }
    mx[x]=max(mx[x],sum-size[x]);
    if(mx[x]<mx[root])root=x;
}
void get_dis(int x,int f)
{
    a[++top]=dis[x];
    for(int i=head[x];i;i=nxt[i])
        if(lst[i]!=f&&!vis[lst[i]])
        {
            dis[lst[i]]=dis[x]+v[i];
            get_dis(lst[i],x);
        }
}
int cal(int x,int now)
{
    dis[x]=now;top=0;
    get_dis(x,0);
    sort(a+1,a+top+1);
    int ans=0,l=1,r=top;
    while(l<r)
        if(a[l]+a[r]<=K)ans+=r-l,l++;else r--;
    return ans;
}   
void solve(int x)
{
    ans+=cal(x,0);
    vis[x]=1;
    for(int i=head[x];i;i=nxt[i])
        if(!vis[lst[i]])
        {
            ans-=cal(lst[i],v[i]);
            sum=size[lst[i]];
            root=0;
            get_root(lst[i],0);
            solve(root);
        }

}
int main()
{
    mx[0]=N;
    n=sc();m=sc();
    for(int i=1;i<=m;i++)
    {
        int x=sc(),y=sc(),z=sc();
        insert(x,y,z);
    }
    K=sc();
    sum=n;
    root=0;
    get_root(1,0);
    solve(root);
    cout<<ans;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值