這題的題意爲求距離爲第k長的編號,在這裏運用算法本身的性質,直接在算法中體現即可:
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;
}