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
#include
#include 
#include
#include
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 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>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>N>>K)
	{
		makeG();
		dfs(K,0);//由于k为起点没有上一个节点,所以不需要规避回头路,所以end设为0 
		cout<


你可能感兴趣的:(SOJ)