SOJ 1024

1024. Magic Island

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

Description

There are N cities and N-1 roads in Magic-Island. You can go from one city to any other. One road only connects two cities. One day, The king of magic-island want to visit the island from the capital. No road is visited twice. Do you know the longest distance the king can go.

Input

There are several test cases in the input
A test case starts with two numbers N and K. (1<=N<=10000, 1<=K<=N). The cities is denoted from 1 to N. K is the capital.

The next N-1 lines each contain three numbers XYD, meaning that there is a road between city-X and city-Y and the distance of the road is D. D is a positive integer which is not bigger than 1000.
Input will be ended by the end of file.

Output

One number per line for each test case, the longest distance the king can go.

Sample Input

3 1
1 2 10
1 3 20

Sample Output

20

Problem Source

ZSUACM Team Member


  比较明显的动态规划的思路。将城市当作有权无向图来处理,dp[k]表示从k出发能走的最大距离,设j为与k相通的城市,所以dp[k]=max(dp[k],dp[j]+distance(j,k) ).

// Problem#: 1024
// Submission#: 5048557
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<cmath>
#include<vector> 
#include<algorithm>
#include<cstring>
using namespace std;
#define MAX_n 10001
struct node{ //新建节点,number保存城市号,distance保存距这个城市的距离 
	int number;
	int distance;
	node(int num,int d)
	{
		number=num;
		distance=d;
	}
};
int dp[MAX_n]; //dp[i]保存了以i为首都能走的最远距离 
vector<node> LINK[MAX_n];//邻接容器数组,若LINK[i]容器中保存的节点即是与城市i相通的城市 
int N,K;//N为城市数,K为首都 

void makeG()//构造图 
{
	memset(dp,0,sizeof(dp));
	for(int i=1;i<=N;++i)
	    LINK[i].clear();//先清空容器 
	int city1,city2,dis;
	for(int i=0;i<N-1;++i)
	{
		cin>>city1>>city2>>dis;
		LINK[city1].push_back(node(city2,dis));//注意是无方向的道路 
		LINK[city2].push_back(node(city1,dis));
	}
}

void dfs(int pos,int end)//利用深搜来动态规划,pos为出发节点,由于不走回头路,所以要设置end形参,代表到达pos之前的节点 
{
	for(int i=0;i<LINK[pos].size();++i)
	{
		if(LINK[pos][i].number==end) continue;//不往回走 
		dfs(LINK[pos][i].number,pos);
		dp[pos]=max(dp[pos],dp[LINK[pos][i].number]+LINK[pos][i].distance);//状态转移方程,从pos出发能走的最长距离为 max(各个子节点能走的最长距离+pos与对应子节点距离) 
	}
}
int main()
{
	while(cin>>N>>K)
	{
		makeG();
		dfs(K,0);//由于k为起点没有上一个节点,所以不需要规避回头路,所以end设为0 
		cout<<dp[K]<<endl;
	}
	return 0;
}                                 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值