hdu3534 树的直径变形
题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=3534
题意:n 之后 n-1条边,l,r,w;求出树上的最长路径以及最长路径的条数。
//思路参考 http://www.cnblogs.com/a-clown/p/6010109.html hdu2196
代码:
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; #define ll long long const int maxn=1e5+5; const int INF=0x3f3f3f3f; struct Edge { int v,l; int next; } edge[maxn<<2]; int head[maxn],k; int ans,t; int d[maxn],num[maxn]; void init() { k=0; memset(head,-1,sizeof(head)); } void addedge(int u,int v,int l) { edge[k].v=v; edge[k].l=l; edge[k].next=head[u]; head[u]=k++; edge[k].v=u; edge[k].l=l; edge[k].next=head[v]; head[v]=k++; } void dfs(int u,int p) { d[u]=0; num[u]=1; for(int i=head[u]; i!=-1; i=edge[i].next) { int v=edge[i].v; if(v==p) continue; dfs(v,u); int tmp=d[v]+edge[i].l; if(tmp+d[u]>ans) { ans=tmp+d[u]; t=num[u]*num[v]; } else if(tmp+d[u]==ans) t+=num[u]*num[v]; if(tmp>d[u]) { num[u]=num[v]; d[u]=tmp; } else if(tmp==d[u]) num[u]+=num[v]; } } int main() { //freopen("in.txt","r",stdin); int n; while(scanf("%d",&n)==1) { init(); int l,r,len; for(int i=1; i<n; i++) { scanf("%d%d%d",&l,&r,&len); addedge(l,r,len); } ans=-INF,t=0; dfs(1,0); printf("%d %d\n",ans,t); } return 0; }

浙公网安备 33010602011771号