我太水了 发现树的直径好像没有弄透彻 然后就重新清理了一遍 把树形dp的做法和两遍dfs的做法重新清理了一遍
树形dp求树的直径
核心:
//f[x]是以x为节点的子树的直径 int f[N];bool vis[N]; void dp(int u) { vis[u]=1; for(rg int i=head[u];i;i=e[i].nxt) { int v=e[i].v,w=e[i].w; if(vis[v]) continue; dp(v); ans=max(ans,f[u]+f[v]+w); f[u]=max(f[u],f[v]+w); } }
树形dp
两遍dfs求树的直径
核心:
void dfs(int u,int fa) { if(f[u]>=maxl) s=u,maxl=f[u]; for(rg int i=head[u];i;i=e[i].nxt) { int v=e[i].v,w=e[i].w; if(v==fa) continue; f[v]=f[u]+w; dfs(v,u); } }
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<cmath> 6 #include<stack> 7 #include<algorithm> 8 using namespace std; 9 #define ll long long 10 #define rg register 11 const int N=10000+5,P=9901,inf=0x3f3f3f3f; 12 int s,sf,maxl; 13 template <class t>void rd(t &x) 14 { 15 x=0;int w=0;char ch=0; 16 while(!isdigit(ch)) w|=ch=='-',ch=getchar(); 17 while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); 18 x=w?-x:x; 19 } 20 21 int head[N],tot=0; 22 struct edge{ 23 int v,w,nxt; 24 }e[N<<1]; 25 void add(int u,int v,int w){ 26 e[++tot].v=v,e[tot].w=w,e[tot].nxt=head[u],head[u]=tot; 27 } 28 29 int f[N]; 30 void dfs(int u,int fa) 31 { 32 if(f[u]>=maxl) s=u,maxl=f[u]; 33 for(rg int i=head[u];i;i=e[i].nxt) 34 { 35 int v=e[i].v,w=e[i].w; 36 if(v==fa) continue; 37 f[v]=f[u]+w; 38 dfs(v,u); 39 } 40 } 41 42 int main() 43 { 44 // freopen("in.txt","r",stdin); 45 //freopen("nocows.out","w",stdout); 46 int u,v,w; 47 memset(f,0,sizeof(f)); 48 while(scanf("%d%d%d",&u,&v,&w)==3) add(u,v,w),add(v,u,w); 49 dfs(1,0);maxl=-1; 50 memset(f,0,sizeof(f));dfs(s,0); 51 printf("%d",maxl); 52 return 0; 53 }