結果

問題 No.19 ステージの選択
ユーザー te-shte-sh
提出日時 2017-02-08 20:38:39
言語 D
(dmd 2.105.2)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 1,395 bytes
コンパイル時間 2,251 ms
コンパイル使用メモリ 156,316 KB
実行使用メモリ 4,388 KB
最終ジャッジ日時 2023-09-03 01:27:44
合計ジャッジ時間 3,174 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

import std.algorithm, std.conv, std.range, std.stdio, std.string;

void main()
{
  auto n = readln.chomp.to!size_t;

  auto li = new int[](n);
  auto uf = new UnionFind!size_t(n);
  auto pi = new size_t[](n);
  pi[] = n;

  foreach (i; n.iota) {
    auto rd = readln.split, l = rd[0].to!int, s = rd[1].to!size_t - 1;
    li[i] = l;
    uf.unite(s, i);
    pi[i] = s;
  }

  size_t[][size_t] ci;
  foreach (i; n.iota) ci[uf.find(i)] ~= i;

  auto vi = new bool[](n);

  auto findLoop(size_t d) {
    auto lp = [pi[d]];
    vi[] = false;
    while (!vi[lp.back]) {
      vi[lp.back] = true;
      lp ~= pi[lp.back];
    }
    return lp ~ pi[lp.back];
  }

  auto findRoot(size_t[] c) {
    auto d = c.front;
    vi[] = false;
    vi[d] = true;
    while (pi[d] < n) {
      if (vi[pi[d]]) return findLoop(d);
      d = pi[d];
      vi[d] = true;
    }
    return [pi[d]];
  }

  auto pt = 0;
  foreach (c; ci.byValue) {
    auto ri = findRoot(c);
    pt += ri.map!(r => li.indexed(c).sum + li[r]).fold!min;
  }

  writefln("%.1f", pt.to!real / 2);
}

class UnionFind(T) {
  T[] p; // parent
  T s; // sentinel

  this(T n) {
    p = new T[](n);
    s = n + 1;
    p[] = s;
  }

  T find(T i) {
    if (p[i] == s) {
      return i;
    } else {
      p[i] = find(p[i]);
      return p[i];
    }
  }

  void unite(T i, T j) {
    auto pi = find(i), pj = find(j);
    if (pi != pj) p[pj] = pi;
  }
}
0