結果

問題 No.160 最短経路のうち辞書順最小
ユーザー te-shte-sh
提出日時 2017-02-06 14:35:32
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 20 ms / 5,000 ms
コード長 1,389 bytes
コンパイル時間 881 ms
コンパイル使用メモリ 114,276 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-03 01:20:08
合計ジャッジ時間 2,274 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 6 ms
4,376 KB
testcase_05 AC 10 ms
4,376 KB
testcase_06 AC 13 ms
4,376 KB
testcase_07 AC 4 ms
4,380 KB
testcase_08 AC 4 ms
4,380 KB
testcase_09 AC 3 ms
4,376 KB
testcase_10 AC 4 ms
4,376 KB
testcase_11 AC 5 ms
4,376 KB
testcase_12 AC 4 ms
4,376 KB
testcase_13 AC 3 ms
4,376 KB
testcase_14 AC 4 ms
4,376 KB
testcase_15 AC 4 ms
4,376 KB
testcase_16 AC 4 ms
4,376 KB
testcase_17 AC 4 ms
4,380 KB
testcase_18 AC 4 ms
4,380 KB
testcase_19 AC 3 ms
4,380 KB
testcase_20 AC 3 ms
4,380 KB
testcase_21 AC 3 ms
4,376 KB
testcase_22 AC 4 ms
4,376 KB
testcase_23 AC 4 ms
4,380 KB
testcase_24 AC 4 ms
4,376 KB
testcase_25 AC 3 ms
4,380 KB
testcase_26 AC 3 ms
4,376 KB
testcase_27 AC 2 ms
4,376 KB
testcase_28 AC 20 ms
4,384 KB
testcase_29 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.algorithm, std.conv, std.range, std.stdio, std.string;
import std.container; // SList, DList, BinaryHeap

void main()
{
  auto rd1 = readln.split.to!(size_t[]), n = rd1[0], m = rd1[1], s = rd1[2], g = rd1[3];
  auto aij = new int[][](n, n);
  foreach (_; m.iota) {
    auto rd2 = readln.split, a = rd2[0].to!size_t, b = rd2[1].to!size_t, c = rd2[2].to!int;
    aij[a][b] = aij[b][a] = c;
  }

  auto di = dijkstra(aij, g);

  size_t[] calc(size_t[] route, int rest) {
    foreach (np; n.iota) {
      if (aij[route.back][np] == 0) continue;
      auto nrest = rest - aij[route.back][np];
      if (np == g && nrest == 0) return route ~ np;
      if (di[np] != nrest) continue;
      auto nroute = calc(route ~ np, nrest);
      if (!nroute.empty) return nroute;
    }
    return [];
  }

  writeln(calc([s], di[s]).to!(string[]).join(" "));
}

struct Edge(T) {
  size_t v;
  T w;
}

T[] dijkstra(T)(T[][] aij, size_t s, T inf = 0) {
  auto n = aij.length;
  auto di = new T[](n);
  di[] = inf;

  auto qi = heapify!("a.w > b.w")(Array!(Edge!T)());

  void addNext(Edge!T e) {
    auto v = e.v, w = e.w;
    di[v] = w;
    foreach (i; n.iota)
      if (aij[v][i] != inf && di[i] == inf)
        qi.insert(Edge!T(i, w + aij[v][i]));
  }

  addNext(Edge!T(s, 0));
  while (!qi.empty) {
    auto e = qi.front; qi.removeFront;
    if (di[e.v] == inf) addNext(e);
  }

  return di;
}
0