poj1741(点分模板)

本文介绍了一种基于图遍历的算法实现,该算法通过构建图结构并进行遍历来求解特定问题。主要内容包括图的表示方法、遍历过程中的节点处理逻辑、以及最终结果的计算方法。

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

#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10010;
int last[maxn],pre[maxn*2],other[maxn*2],w[maxn*2],t,vis[maxn];
void add(int x,int y,int z){++t;pre[t]=last[x];last[x]=t;other[t]=y;w[t]=z;}
int cnt,root,d[maxn],siz[maxn],f[maxn],sizz,q[maxn];
int x,y,z,n,m,k,ans;
void getroot(int x,int fa){
    siz[x]=1;f[x]=0;
    for(int i=last[x];i;i=pre[i]){
        int v=other[i];
        if(v==fa||vis[v])continue;
        getroot(v,x);
        siz[x]+=siz[v];
        f[x]=max(f[x],siz[v]);
    }
    f[x]=max(f[x],sizz-siz[x]);
    if(f[x]<f[root])root=x;
}
void getdis(int x,int fa){
    q[++cnt]=d[x];
    for(int i=last[x];i;i=pre[i]){
        int v=other[i];
        if(v==fa||vis[v])continue;
        d[v]=d[x]+w[i];
        getdis(v,x);
    }
}
int calc(int x,int init){
    cnt=0;d[x]=init;
    getdis(x,0);
    sort(q+1,q+cnt+1);
    int res=0;
    for(int l=1,r=cnt;l<r;){
        if(q[l]+q[r]<=k){res+=r-l;l++;}
        else r--;
    }
    return res;
}
void solve(int x){
    ans+=calc(x,0);
    vis[x]=1;
    for(int i=last[x];i;i=pre[i]){
        int v=other[i];
        if(vis[v])continue;
        ans-=calc(v,w[i]);
        f[0]=sizz=siz[v];
        root=0;
        getroot(v,0);
        solve(root);
    }
}
int main(){
    while(scanf("%d%d",&n,&k)!=EOF){
        if(n==0&&k==0)break;
        memset(last,0,sizeof(last));
        memset(vis,0,sizeof(vis));
        t=0;
        for(int i=1;i<n;++i){
            scanf("%d%d%d",&x,&y,&z);
            add(x,y,z);add(y,x,z);
        }
        f[0]=sizz=n;ans=root=0;
        getroot(1,0);
        solve(root);
        printf("%d\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/dibaotianxing/p/8066994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值