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 theK-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 andM (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 followingM lines,A, B, C, which descript one road. A and B are the two cities that connected by that road, andC 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 integerK (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;
}
		


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章