HDU3534 Tree(树形dp)

4 篇文章 0 订阅
4 篇文章 0 订阅

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3534


Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1144    Accepted Submission(s): 346


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
 
题意:找出给定树的最长路径和最长路径数目。

思路:在深搜的时候记录下来以当前点为根的最长路径和个数,同时更新maxlen 和计数器cnt。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
struct node {
    int v, w;
    node(int v, int w) {
        this->v=v;
        this->w=w;
    }
};
int d[maxn], num[maxn];
int maxlen, cnt;
vector<node> rec[maxn];
void dfs(int pre, int fa) {
    num[pre] = 1;
    for(int i = 0; i < rec[pre].size(); i++) {
        int t = rec[pre][i].v, w = rec[pre][i].w;
        if(t == fa) continue;
        dfs(t, pre);
        // 更新maxlen 和 cnt
        if(d[pre] + d[t] + w > maxlen) {  
            maxlen = d[pre] + d[t] + w;
            cnt = num[pre]*num[t];
        } else if(d[pre] + d[t] + w == maxlen) {
            cnt += num[pre]*num[t];
        }
        // 记录更新以pre为根的最长路径的值和个数
        if(d[t] + w > d[pre]) {          
            d[pre] = d[t] + w;
            num[pre] = num[t];
        } else if(d[t] + w == d[pre]) {
            num[pre] += num[t];
        }

    }
}
int main() {
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 0; i <= n; i++) rec[i].clear();
        cnt = maxlen = 0;
        memset(d, 0, sizeof(d));
        for(int i = 0; i < n-1; i++) {
            int a, b, c;
            scanf("%d %d %d", &a, &b, &c);
            rec[a].push_back(node(b, c));
            rec[b].push_back(node(a, c));
        }
        dfs(1, -1);
        printf("%d %d\n", maxlen, cnt);
    }
    return 0;
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值