zoukankan      html  css  js  c++  java
  • 【POJ2631】Roads in the North 树的直径

    题目大意:给定一棵 N 个节点的边权无根树,求树的直径。

    代码如下

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    const int maxn=1e4+10;
    
    struct node{
    	int nxt,to,w;
    }e[maxn<<1];
    int tot=1,head[maxn];
    inline void add_edge(int from,int to,int w){
    	e[++tot].nxt=head[from],e[tot].to=to,e[tot].w=w,head[from]=tot;
    }
    int d1[maxn],d2[maxn],ans;
    
    void dfs(int u,int fa){
    	for(int i=head[u];i;i=e[i].nxt){
    		int v=e[i].to,w=e[i].w;if(v==fa)continue;
    		dfs(v,u);
    		if(d1[v]+w>d1[u])d2[u]=d1[u],d1[u]=d1[v]+w;
    		else d2[u]=max(d2[u],d1[v]+w);
    	}
    }
    
    void solve(){
    	dfs(1,0);
    	for(int i=1;i<=10000;i++)ans=max(ans,d1[i]+d2[i]);
    	printf("%d
    ",ans);
    }
    
    int main(){
    	int from,to,w;
    	while(scanf("%d%d%d",&from,&to,&w)!=EOF){
    		add_edge(from,to,w),add_edge(to,from,w);
    	}
    	solve();
    	return 0;
    }
    
  • 相关阅读:
    HTTPS原理浅析
    Java8 HashMap源码分析
    Java8 ArrayList源码分析
    Java反射
    Java泛型
    Tensorflow卷积神经网络
    Java8 Stream简介
    java.io与网络通信
    Python实现RNN
    域名系统DNS简介
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10020707.html
Copyright © 2011-2022 走看看