您的位置:首页 > Web前端 > Node.js

Light OJ:1094 Farthest Nodes in a Tree(树状DP+统计树的最大直径)

2016-08-02 21:47 316 查看
1094 - Farthest Nodes in a Tree



 
  

PDF (English)StatisticsForum
Time Limit: 2 second(s)Memory Limit: 32 MB
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

Output for 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

Case 1: 100

Case 2: 80

Notes

Dataset is huge, use faster i/o methods.

题目大意:给你一个数的节点连接信息和节点间的权值,问这个树的最大直径是多少。

解题思路:新学的结构体链表模板(树状DP?网上这么叫的),求树的最大直径,先随意找个点,然后找到这个点能达到的最远点s,再以s为起点,找s能到达的最远点t,那么s-t的距离即为该数的最大直径,网上很多证明的。
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int from,to,val,last;//last是该边所连接的上条边
}bian[60020];
int dis[30010];//标记某点到每点的距离
int head[30010];//标记每个点在哪条边出现,会更新,但是只要找到该点所在的某个边即可通过链表来找与它相连的边了
int vis[30010];//标记访问过的点
int n;
int num;
int start; //第一次搜索到最远的那个元素 (s点)
void add(int s,int e,int power)//标记某些数字出现在第几行,存到表头head中
{
bian[num].from=s;
bian[num].to=e;
bian[num].val=power;
bian[num].last=head[s];//如果它没有上条连接的边 就标记成-1   有的话就标记成上条变是第几条
head[s]=num;//更新下s所在的第几条边,num是边的号码
num++;
}
void bfs(int x)
{
int r=x;
queue<int>q;
q.push(r);
vis[r]=1;
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(int i=head[tmp];i!=-1;i=bian[i].last)
{
int tmp2=bian[i].to;
if(vis[tmp2]==0&&dis[tmp2]<dis[tmp]+bian[i].val)//找到当前边加哪个边后变长
{
dis[tmp2]=dis[tmp]+bian[i].val;
vis[tmp2]=1;
q.push(tmp2);
}
}
}
int max=0;
for(int i=0;i<n;i++)
{
if(dis[i]>max)
{
max=dis[i];
start=i;
}
}
}
int main()
{
int t;
scanf("%d",&t);
int hao=1;
while(t--)
{
memset(head,-1,sizeof(head));
scanf("%d",&n);
num=0;
for(int i=0;i<n-1;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);//求数的最大直径必须打双向的链表
add(y,x,z);
}
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
bfs(0);//随意找个点
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
bfs(start);
printf("Case %d: %d\n",hao++,dis[start]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模板