LightOJ 1094 Farthest Nodes in a Tree(dfs)
来源:互联网 发布:tcl网络电视如何看直播 编辑:程序博客网 时间:2024/06/08 17:54
题意
一句话题意:就是给出一颗树,让你求树的直径。
思路
这是一道大水题,只要dfs两遍就行了。对于第一遍dfs,随意找一个点,然后找到离这个点最远的一个点,再从这个最远的点再次dfs找到最远的距离,就是树的直径了。
Code
#pragma GCC optimize(3)#include<bits/stdc++.h>using namespace std;typedef long long ll;inline void readInt(int &x) { x=0;int f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); x*=f;}inline void readLong(ll &x) { x=0;int f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); x*=f;}/*================Header Template==============*/const int maxn=30005;struct Edge { int u,v,w; Edge(){} Edge(int a,int b,int c):u(a),v(b),w(c){}};int T;vector<int> G[maxn];vector<Edge> edges;int d[maxn],ind=0;inline void dfs(int u,int fa) { if(d[ind]<d[u]) ind=u; for(unsigned i=0;i<G[u].size();i++) { Edge &e=edges[G[u][i]]; int v=e.v,w=e.w; if(v==fa) continue; d[v]=d[u]+w; dfs(v,u); }}int main() { readInt(T); for(int C=1;C<=T;C++) { int n,a,b,c; readInt(n); for(int i=0;i<n;i++) G[i].clear(); edges.clear(); for(int i=1;i<n;i++) { readInt(a); readInt(b); readInt(c); edges.push_back(Edge(a,b,c)); G[a].push_back(edges.size()-1); edges.push_back(Edge(b,a,c)); G[b].push_back(edges.size()-1); } memset(d,0,sizeof d); ind=0; dfs(0,-1); memset(d,0,sizeof d); dfs(ind,-1); printf("Case %d: %d\n",C,d[ind]); }}
阅读全文
0 0
- LightOJ 1094 Farthest Nodes in a Tree(dfs)
- LightOJ 1094 - Farthest Nodes in a Tree【树的直径】
- LightOJ - 1094 Farthest Nodes in a Tree(树的直径)
- LightOJ 1094 Farthest Nodes in a Tree 树的直径
- 【 LightOJ - 1094】Farthest Nodes in a Tree(求树的直径)链式向前星 + DFS or BFS
- lightoj 1257 - Farthest Nodes in a Tree (II) 树直径
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- LightOJ 1094-1094 - Farthest Nodes in a Tree【树的直径模板】
- Lightoj 1094 - Farthest Nodes in a Tree 【树的直径 裸题】
- Lightoj 1094 - Farthest Nodes in a Tree 【树的直径裸题】
- LightOJ--1094-- Farthest Nodes in a Tree(树的直径裸题)
- 【LightOJ】1094 - Farthest Nodes in a Tree(树的直径)
- lightoj-1094-Farthest Nodes in a Tree【树的直径模板】
- Light OJ 1094 - Farthest Nodes in a Tree
- Light OJ 1094 + Farthest Nodes in a Tree(搜索)
- Ubuntu上安装wine进行apt-get update时遇到的问题
- vim 插件 (安装 and 用法)
- Android使用ShareSDK实现微信第三方登录中要获取unionid的方法
- java应用MongoDB简单操作
- Ones and Zeroes 问题及解法
- LightOJ 1094 Farthest Nodes in a Tree(dfs)
- getopt、getopt_long和getopt_long_only
- C# 钉钉api接口开发(三) 免登录及自动刷新AccessToken
- 求平均数的几种方法
- ElasticSearch基础
- BZOJ1827 [Usaco2010 Mar]gather 奶牛大集会
- Uiautomator的基础对象
- Android图片加载库的封装实战
- 数据结构实验之链表一:顺序建立链表