lightoj1094Farthest Nodes in a Tree
来源:互联网 发布:淘宝店铺处置期 编辑:程序博客网 时间:2024/06/05 03:34
Description
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.
Output
For each case, print the case number and the maximum distance.
Sample Input
2
4
0 1 20
1 2 30
2 3 50
5
0 2 20
2 1 10
0 3 29
0 4 50
Sample Output
Case 1: 100
Case 2: 80
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int MAX=30000+10;
const int MAXN=2*30000+10;
struct Edge{
int from,to,val,next;
}edge[MAXN];
int dist[MAX];
int vis[MAX];
int head[MAX];
int top,ans,node;
void init()
{
top=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int w)
{
Edge E={u,v,w,head[u]};
edge[top]=E;
head[u]=top++;
}
void bfs(int sx)
{
queue<int>q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
node=sx;
ans=0;
vis[sx]=1;
q.push(sx);
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i!=-1;i=edge[i].next)
{
Edge E=edge[i];
if(!vis[E.to])
{
dist[E.to]=dist[u]+E.val;
if(ans<dist[E.to])
{
ans=dist[E.to];
node=E.to;
}
vis[E.to]=1;
q.push(E.to);
}
}
}
}
int main()
{
int t,n,a,b,c;
scanf("%d",&t);
int l=1;
while(t--)
{
init();
scanf("%d",&n);
n--;
while(n--)
{
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,c);
addedge(b,a,c);
}
bfs(1);
bfs(node);
printf("Case %d: %d\n",l++,ans);
}
return 0;
}
- lightoj1094Farthest Nodes in a Tree
- LightOJ1094Farthest Nodes in a Tree(BFS+树的直径)
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- Farthest Nodes in a Tree
- E - Farthest Nodes in a Tree
- E - Farthest Nodes in a Tree
- Light OJ 1094 - Farthest Nodes in a Tree
- Light OJ 1094 + Farthest Nodes in a Tree(搜索)
- LightOJ 1094 - Farthest Nodes in a Tree【树的直径】
- LightOJ - 1094 Farthest Nodes in a Tree(树的直径)
- lightoj 1257 - Farthest Nodes in a Tree (II) 树直径
- Farthest Nodes in a Tree(树的直径)
- Farthest Nodes in a Tree(树的直径)
- 【Light oj 1094 Farthest Nodes in a Tree】
- find distance between two nodes in a binary tree
- LightOJ 1094 Farthest Nodes in a Tree 树的直径
- poj2361Roads in the North
- 14个无往不胜的心理定律,心理暗示真的很重要。
- ActiveMQ实现负载均衡+高可用部署方案
- Json数据转换成实体类
- android-ListView实现复杂界面
- lightoj1094Farthest Nodes in a Tree
- iptables 设置
- 访问修饰符·this关键字
- 1,从零开始搭建SSHM开发框架(环境准备)
- 【转】APPIUM API
- Android应用签名
- 程序人生之六:写在 2010 年最后一晚,我这两年的工作总结
- maven项目 没有或移除Maven Dependencies后怎么在添加进去(转载)
- CUDA 7.5 安装