Problem Description
In the Data structure class of HEU, the teacher asks one problem: How to find the longest path of one tree and the number of such longest path?
Input
There are several test cases. The first line of each case contains only one integer N, means there are N nodes in the tree. N-1 lines follow, each line has three integers w,v and len, indicate that there is one edge between node w and v., and the length of the edge is len.
Output
For each test case, output the length of longest path and its number in one line.
Sample Input
4
1 2 100
2 3 50
2 4 50
4
1 2 100
2 3 50
3 4 50
Sample Output
150 2
200 1
给出一颗n个节点的树,每条边对应一个长度,求出距离最大的两个节点之间长度,并找出一共有多少个顶点对。
就是求树的直径和圆点,DFS可做,树型DP也可做。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int INF=0x3f3f3f3f;
const int N=500000;
int head[N],num,Len[N],ans,node[N],k;
struct edge
{
int ed,w,next;
}e[N*2];
void addedge(int x,int y,int w)
{
e[num].ed=y;e[num].w=w;e[num].next=head[x];head[x]=num++;
e[num].ed=x;e[num].w=w;e[num].next=head[y];head[y]=num++;
}
void dfs(int u,int fa)
{
int i,v,temp;
Len[u]=0;//最长边
node[u]=1;//最长边的个数
for(i=head[u];i!=-1;i=e[i].next)
{
v=e[i].ed;
if(v==fa)continue;
dfs(v,u);
temp=Len[v]+e[i].w;
if(temp+Len[u]>ans)//最长边经过v
{
k=node[v]*node[u];
ans=temp+Len[u];
}
else if(temp+Len[u]==ans)
k+=node[v]*node[u];
if(Len[u]<temp)//更新最长边
{
Len[u]=temp;
node[u]=node[v];
}
else if(Len[u]==temp)//更新最长边的个数
node[u]+=node[v];
}
}
int main()
{
int n,i,x,y,w;
while(scanf("%d",&n)!=-1)
{
memset(head,-1,sizeof(head));
num=0;
for(i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&w);
addedge(x,y,w);
}
ans=-INF;
k=0;
dfs(1,0);
printf("%d %d\n",ans,k);
}
return 0;
}