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