HDU 2544 (Djikstra)

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=2544

简单的最短路径问题,用Djikstra即可解决!

代码如下:

#include <cstdio>
#include <cstring>
using namespace std;

const int MAX = 101;
const int INF = 1000000001;
int map[MAX][MAX];
int visited[MAX];
int dist[MAX];

int djikstra(int v, int n);

int main()
{
  int n, m;
  int i;
  int r_i, r_j, weight;
  while(scanf("%d%d", &n, &m) != EOF && (n || m))
  {
    memset(map, INF, sizeof(map));
    for(i = 1; i <= n; i++)
    {
      map[i][i] = 0;
    }
    for(i = 1; i <= m; i++)
    {
      scanf("%d%d%d", &r_i, &r_j, &weight);
      map[r_i][r_j] = weight;
      map[r_j][r_i] = weight;
    }
    djikstra(1, n);
  }
  return 0;
}

int djikstra(int v, int n)
{
  int i, j;
  int min, sum = 0, k;
  memset(visited, 0, sizeof(visited));
  for(i = 1; i <= n; i++)
  {
    dist[i] = map[v][i];
  }
  visited[v] = 1;
  for(i = 2; i <= n; i++)
  {
    min = INF;
    for(j = 1; j <=n; j++)
    {
      if(!visited[j] && dist[j] < min)
      {
        min = dist[j];
        k = j;
      }
    }
    if(min == INF)
    {
      break;
    }
    sum = min;
    if(k == n)
    {
      break;
    }
    visited[k] = 1;
    for(j = 1; j <= n; j++)
    {
      if(!visited[j] && dist[j] > map[k][j] + dist[k])
      {
        dist[j] = map[k][j] + dist[k];
      }
    }
  }
  printf("%d\n", sum);
  return 0;
}

posted @ 2012-08-02 16:55  山路水桥  阅读(408)  评论(0编辑  收藏  举报