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 */