HDU 2544 最短路

來源:互聯網
上載者:User

標籤:

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 最短路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.