您的位置:首页 > 编程语言 > PHP开发

zju 2870

2010-06-29 10:36 363 查看
/*
 2870.   The K-th City
--------------------------------------------------------------------------------
Time Limit: 1.0 Seconds   Memory Limit: 65536K
Total Runs: 2104   Accepted Runs: 753

--------------------------------------------------------------------------------

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

Dijkstra
基本思想:贪心
设置一个顶点集合S,从源点到S中顶点的最短路径权值已经确定,通过反复从V-S中选取具有最短路径估计的顶点u,将u加入S中,并更新所有u的出边,求得最短路径
void  dijkstra( ) {
 初始化S={空集}
 dist[s] = 0; 其余dist值为正无穷大
 for (k = 1; k < n; ++k){
  取出不在S中的最小的dist[i];
  for (所有不在S中且与i相邻的点j)
  if (dist[j] > dist[i] + cost[i][j])
   dist[j] = dist[i] + cost[i][j];
  S = S + {i};
 }
}
*/
#include<iostream>//917572 2010-06-29 10:34:07 Accepted 2870 C++ 1.1K 0'00.02" 1368K huixisheng
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX = 205;
const int d = 0X7fffffff;

int cost[MAX][MAX];
int dis[MAX];
bool hash[MAX];
int n;

void Dijkstra(int last)
{
 memset(hash, false, sizeof(hash));
 int i, j, k, dd, t;
 hash[0] = true;
 for(i = 1; i <= last; i++)
 {
  dd = d;
  for(j = 0; j < n; j++)
  {
   if(!hash[j] && dis[j] < dd)
   {
    t = j;
    dd = dis[j];
   }
  }
  for(k = 1; k < n; k++)
  {
   if(!hash[k] && cost[t][k] != d && dis[k] > cost[t][k] + dis[t])
    dis[k] = cost[k][t] + dis[t];
  }
  hash[t] = true;
  if(i == last)
   //cout<<dis[k]<<endl;
   printf("%d/n", t);
 }
}

int main()
{
 int m, i, j;
 while(scanf("%d", &n ) != EOF && n != 0)
 {
  scanf("%d", &m);
  for(i = 0; i < n; i++)
  for(j = 0; j < n; j++)
  {
   if(i == j)
    cost[i][j] = 0;
   else
    cost[i][j] = d;
  }
  int a, b, c;
  for(i = 0; i < m; i++)
  {
   scanf("%d %d %d", &a, &b, &c);
   cost[a][b] = c;
   cost[b][a] = c;
  }
  for(i = 0; i < n ; i++)
   dis[i] = cost[0][i];
   
  int th;
  scanf("%d", &th);
  Dijkstra(th);
 }
 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息