码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2544 最短路

时间:2016-05-06 12:47:33      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

Description

就是最短路

Algorithm

Dijkstra
我就用最水的 未加优化的做了一下 理论时间复杂度O(V^2)
V为顶点数
后来想想光一开始赋值INF就用了V^2实在不划算
就做了个hasCost的优化,空间换时间,不过也没有快多少
还是要学优先队列的优化啊

Code

第一版

import java.util.Arrays;
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner cin = new Scanner(System.in);
    for (;;) {
      int n = cin.nextInt();
      int m = cin.nextInt();
      if (n == 0) break;
      int[][] cost = new int[n][n];
      for (int i = 0; i < n; i++) {
        Arrays.fill(cost[i], Integer.MAX_VALUE / 2);
        cost[i][i] = 0;
      }
      for (int i = 0; i < m; i++) {
        int a = cin.nextInt() - 1;
        int b = cin.nextInt() - 1;
        int c = cin.nextInt();
        cost[a][b] = c;
        cost[b][a] = c;
      }
      int[] d = new int[n];
      Arrays.fill(d, Integer.MAX_VALUE / 2);
      boolean[] used = new boolean[n];
      d[0] = 0;
      for (;;) {
        int v = -1;
        for (int u = 0; u < n; u++) {
          if (!used[u] && (v == -1 || d[u] < d[v])) v = u;
        }
        if (v == -1) break;
        used[v] = true;
        for (int u = 0; u < n; u++) {
          d[u] = Math.min(d[u], d[v] + cost[v][u]);
        }
      }
      System.out.println(d[n - 1]);
    }
  }
}

第二版

import java.util.Arrays;
import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    final int INF = Integer.MAX_VALUE / 2;
    Scanner cin = new Scanner(System.in);
    for (;;) {
      int n = cin.nextInt();
      int m = cin.nextInt();
      if (n == 0) break;
      int[][] cost = new int[n][n];
      boolean[][] hasCost = new boolean[n][n];
      for (int i = 0; i < m; i++) {
        int a = cin.nextInt() - 1;
        int b = cin.nextInt() - 1;
        int c = cin.nextInt();
        cost[a][b] = c;
        cost[b][a] = c;
        hasCost[a][b] = true;
        hasCost[b][a] = true;
      }
      int[] d = new int[n];
      Arrays.fill(d, INF);
      boolean[] used = new boolean[n];
      d[0] = 0;
      for (;;) {
        int v = -1;
        for (int u = 0; u < n; u++) {
          if (!used[u] && (v == -1 || d[u] < d[v])) v = u;
        }
        if (v == -1) break;
        used[v] = true;
        for (int u = 0; u < n; u++) {
          int w = d[v] + cost[v][u];
          if (!hasCost[v][u]) w = INF;
          d[u] = Math.min(d[u], w);
        }
      }
      System.out.println(d[n - 1]);
    }
  }
}

HDU 2544 最短路

标签:

原文地址:http://blog.csdn.net/yyecust/article/details/51329382

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!