dijstra算法 2870. The K-th City


这题的题意为求距离为第k长的编号,在这里运用算法本身的性质,直接在算法中体现即可:

—1.Dijkstra算法每次都是取出目前d值最小的顶点进行更新,即每次确定一个顶点u,即每次找到的结果都是到该点的最短路径,而且第一次得到最短的、第二次得到第二短的……第K次得到第K短的
—2.因此不必算出到所有点的最短路径,只要算到第K次即可


Given a map of your country, there are N cities. The cities are labeled as 0, 1, ..., N - 1, and you live in city 0. Can you calculate out the K-th nearest city form you? If two or more cities have the same distance form you, you may assume that the city with smaller label is nearer than the city with bigger one.

Input

There are several cases. The first line of each case is two integers N and M (1 ≤ N ≤ 200, 0 ≤ M ≤ 10000), which is the number of cities in your country and the total number of roads in your country. There are three integers in each of the following M lines, A, B, C, which descript one road. A and B are the two cities that connected by that road, and C is the length of that road (1 ≤ C ≤ 2000). The roads are of both directions, and no two roads connect two same cities. There is at least one path between any two cities. At the last line of each case is a single integer K (1 ≤ K < N).

The last case is followed by a line with a single 0.

Output

Print the label of the K-th nearest city.

Sample Input

4 3
0 1 120
0 2 180
1 3 40
3
4 3
0 1 120
0 3 60
3 2 30
1
0

Sample Output

2
3

#include<iostream>
#include<cstring>
#include<algorithm>
#define inf 1000000
#define num 201
using namespace std;
int map[num][num],dist[num],flag[num],N,M,k;
int dijstra()
{
	int tmp,i,j;
	for(i=0;i<N;i++)
	{
		dist[i]=inf;
		flag[i]=0;
	}
	dist[0]=0;
	//flag[0]=1;
	for( i=0;i<N;i++)
	{
		int min=inf;
		for(j=0;j<N;j++)
		{
			if(!flag[j]&&dist[j]<min)
			{
			//	cout<<"111"<<endl;
				tmp=j;
				min=dist[j];
			}
		}
		if(i==k)
			return tmp;
		//cout<<min<<endl;
		//cout<<tmp<<endl;
		flag[tmp]=1;
		for(j=0;j<N;j++)
		{
			if(!flag[j]&&dist[j]>dist[tmp]+map[tmp][j])
				dist[j]=dist[tmp]+map[tmp][j];
		}
		
	}
}
int main()
{
	int a,b,c;
	while(cin>>N>>M)
	{
		if(N==0)
			break;
		for(int i=0;i<N;i++)
		{
			for(int j=0;j<N;j++)
			{
				if(i==j)
					map[i][j]=0;
				else
					map[i][j]=inf;
			}
		}
		for(int i=0;i<M;i++)
		{
			cin>>a>>b>>c;
			map[a][b]=map[b][a]=c;
		}
		cin>>k;
		cout<<dijstra()<<endl;
		//dijstra();
	//	for(int i=0;i<N;i++)
			//cout<<dist[i]<<endl;
	}
	return 0;
}
		


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值