Day2-T4

原题目

  当然这是原题+,要输路径的。所以必须DFS。

  Describe:DP or DFS

  code:

#include<bits/stdc++.h>
using namespace std;
long long n,x,y,z,nxt[50005],tot,fa[50005],W[50005],son[50005],fir[50005],dis[50005],q[50005],ans,maxn;
bool vis[50005],vis2[50005];
inline long long read(){
    long long ret=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9') {if (ch=='-') f=-f;ch=getchar();}
    while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
    return ret*f;
}
inline void write(long long x){
    if(x<0){putchar('-'),write(-x);return;}
    if(x/10)write(x/10);putchar(x%10+'0');
}
inline void add(int a,int b,int w){
    son[++tot]=b;
    nxt[tot]=fir[a];
    fa[tot]=a;
    fir[a]=tot;
    W[tot]=w;
    
    son[++tot]=a;
    nxt[tot]=fir[b];
    fa[tot]=b;
    fir[b]=tot;
    W[tot]=w;
}
inline void spfa(int s){
    memset(vis,0,sizeof(vis));
    memset(dis,0,sizeof(dis));
    memset(vis2,0,sizeof(vis2));
    
    long long h=0,t=1;q[1]=s;
    while(h!=t){
        h=h%n+1;long long K=q[h];vis[K]=0;
        for(int i=fir[K];i;i=nxt[i]){
            int to=son[i];
            if(dis[K]+W[i]>dis[to]&&!vis2[i]){
                dis[to]=dis[K]+W[i],vis2[i]=1;
                if(son[i-1]==K&&fa[i-1]==to)
                vis2[i-1]=1;else vis2[i+1]=1;
                if(!vis[to])t=t%n+1,q[t]=to,vis[to]=1;
            }
        }
    }
}
int main(){
    freopen("tree.in","r",stdin);
    freopen("tree.out","w",stdout);
    n=read();for(int i=1;i<=n-1;i++)x=read(),y=read(),z=read(),add(x,y,z);               //建图
    spfa(1);for(int i=2;i<=n;i++)if(dis[i]>dis[maxn])maxn=i;                             //根据题意,SPFA找最远点
    spfa(maxn);for(int i=1;i<=n;i++)ans=max(ans,dis[i]);write(ans);                      //SPFA找距离
}
/*
4
1 2 10
1 3 12
1 4 15
*/

 

  

 

转载于:https://www.cnblogs.com/sroht/p/9885111.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值