[HDU 3848]CC On The Tree[dfs]

题目链接: [HDU 3848]CC On The Tree[dfs]

题意分析:

求树上任意两个叶子结点之间距离的最小值。

解题思路:

考虑从树上任意一个非叶子结点开始dfs遍历,求出距离该点最短和次短的两个叶子节点,更新答案:ans = min(ans, 最短 + 次短)。如果每一个都这样求很容易就超时了,可以发现,之前的结果可以接着用,比如新结点遍历到了之前已经遍历过的结点,那么只要返回到这个结点最近的叶子结点距离即可,即返回最短,整个是个递归的子结构。

个人感受:

20天前WA的题,坚信自己的算法是对的。今天重新拿出来,原来是少判断了可能越界的情况= =我真是醉了!!!1h debug!!!

具体代码如下:

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

const int INF = 0x7f7f7f7f;
const int MAXN = 1e4 + 111;

struct Edge{
    int to, w;
    Edge(int _to, int _w):to(_to), w(_w){}
};

vector<vector<Edge> > G;
int ans;

int dfs(int u, int fa)
{
    if (G[u].size() <= 1) return 0;

    vector<int> temp; //存储所有的子状态
    for (int i = 0; i < G[u].size(); ++i) {
        if (G[u][i].to == fa) continue;
        temp.push_back(dfs(G[u][i].to, u) + G[u][i].w);
    }
    sort(temp.begin(), temp.end());
    // 就是这里!!!!!本地运行越界也无所谓,真是醉了,然而去掉这句就WA
    if (temp.size() > 1){
        ans = min(ans, temp[0] + temp[1]);
    }
    return temp[0];
}

int main()
{
    int n, u, v, w;
    while (~scanf("%d", &n) && n)
    {
        G.clear();
        G.resize(n + 2);
        ans = INF;
        for (int i = 0; i < n - 1; ++i) {
            scanf("%d%d%d", &u, &v, &w);
            G[u].push_back(Edge(v, w));
            G[v].push_back(Edge(u, w));
        }

        for (int i = 1; i <= n; ++i) {
            if (G[i].size() > 1) {
                dfs(i, -1);
                break;
            }
        }

        if (n == 2) ans = w;

        printf("%d\n", ans);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值