結果

問題 No.416 旅行会社
ユーザー te-shte-sh
提出日時 2017-10-26 10:59:16
言語 D
(dmd 2.107.1)
結果
WA  
実行時間 -
コード長 2,074 bytes
コンパイル時間 862 ms
コンパイル使用メモリ 100,488 KB
実行使用メモリ 25,200 KB
最終ジャッジ日時 2023-09-03 16:28:23
合計ジャッジ時間 9,543 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

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

void main()
{
  auto rd = readln.split.to!(int[]), n = rd[0], m = rd[1], q = rd[2];
  auto e1 = loadEdges(m), e2 = loadEdges(q);

  auto uf = UnionFind!int(n);

  auto e2s = e2.dup.sort!("a.u == b.u ? a.v < b.v : a.u < b.u");
  foreach (ei; e1.filter!(ei => !e2s.contains(ei))) {
    uf.unite(ei.u, ei.v);
  }

  auto ans = new int[](n);
  ans[] = -1;

  foreach_reverse (i, ei; e2) {
    if (uf[ei.u] == uf[0] && uf[ei.v] != uf[0])
      foreach (v; uf.nodes[uf[ei.v]]) ans[v] = i.to!int+1;
    if (uf[ei.v] == uf[0] && uf[ei.u] != uf[0])
      foreach (u; uf.nodes[uf[ei.u]]) ans[u] = i.to!int+1;
    uf.unite(ei.u, ei.v);
  }

  foreach (i; 1..n) writeln(ans[i]);
}

struct Edge { int u, v; }

auto loadEdges(size_t m)
{
  auto e = new Edge[](m);
  foreach (i; 0..m) {
    auto rd = readln.splitter;
    auto a = rd.front.to!int-1; rd.popFront();
    auto b = rd.front.to!int-1;
    e[i] = Edge(a, b);
  }
  return e;
}

struct UnionFind(T)
{
  import std.algorithm, std.range;

  T[] p; // parent
  const T s; // sentinel
  const T n;
  T countForests; // number of forests
  T[] countNodes; // number of nodes in forests
  T[][] nodes;

  this(T n)
  {
    this.n = n;
    s = n;
    p = new T[](n);
    p[] = s;
    countForests = n;
    countNodes = new T[](n);
    countNodes[] = 1;
    nodes = new T[][](n);
    foreach (i; 0..n) nodes[i] = [i];
  }

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

  bool unite(T i, T j)
  {
    auto pi = this[i], pj = this[j];
    if (pi != pj) {
      p[pj] = pi;
      --countForests;
      countNodes[pi] += countNodes[pj];
      nodes[pi] ~= nodes[pj];
      nodes[pj] = [];
      return true;
    } else {
      return false;
    }
  }

  auto countNodesOf(T i) { return countNodes[this[i]]; }
  bool isSame(T i, T j) { return this[i] == this[j]; }

  auto groups()
  {
    auto g = new T[][](n);
    foreach (i; 0..n) g[this[i]] ~= i;
    return g.filter!(l => !l.empty);
  }
}
0