Sicily 1024 Magic Island

本文介绍了一种求解图中从指定起点出发的最长路径的方法。通过将双向边转换为单向边,并使用深度优先搜索(DFS)算法遍历图,最终找到从指定起点出发的最长路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    N个结点N-1条边无孤立点,说明这是图的最小生成树。首先将双向边改为单向边,再DFS搜索,两者可同时进行。

#include <iostream>
#include <set>
#include <vector>

using namespace std;

typedef set<pair<int, int> > Node;

void traverse(vector<Node> &tree, int root, int &longest, int pathCost) {
    if (tree[root].empty()) {
        if (pathCost>longest)
            longest=pathCost;
    }
    else {
        for (Node::iterator iter=tree[root].begin();
            iter!=tree[root].end(); iter++) {
                tree[(*iter).first].erase(make_pair(root, (*iter).second));	// 变双向边为单向边
                traverse(tree, (*iter).first, longest, pathCost+(*iter).second);	// DFS
            }
    }
}

int main() {
    int N, K;
    while (cin>>N) {
        cin>>K;
        vector<Node> tree(N+1);
        while (--N) {
            int first, second, distance;
            cin>>first>>second>>distance;
            tree[first].insert(make_pair(second, distance));
            tree[second].insert(make_pair(first, distance));
        }
        int longest=0;
        traverse(tree, K, longest, 0);
        cout<<longest<<"\n";
    }
    return 0;
}                          

// by wbchou
// Jan 31th , 2013

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值