結果

問題 No.517 壊れたアクセサリー
ユーザー te-shte-sh
提出日時 2018-01-26 10:52:30
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,763 bytes
コンパイル時間 566 ms
コンパイル使用メモリ 94,316 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-03 18:22:06
合計ジャッジ時間 2,252 ms
ジャッジサーバーID
(参考情報)
judge14 / 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,384 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,380 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 1 ms
4,380 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 1 ms
4,376 KB
testcase_15 AC 1 ms
4,380 KB
testcase_16 AC 1 ms
4,376 KB
testcase_17 AC 1 ms
4,380 KB
testcase_18 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
T[] readArray(T)(size_t n){auto a=new T[](n),r=readln.splitter;foreach(ref v;a){v=r.front.to!T;r.popFront;}return a;}
T[] readArrayM(T)(size_t n){auto a=new T[](n);foreach(ref v;a)v=readln.chomp.to!T;return a;}

void main()
{
  int n; readV(n);
  auto a = readArrayM!string(n);
  int m; readV(m);
  auto b = readArrayM!string(m);

  auto t = a.map!(ai => ai.length.to!int).sum;
  auto c = new char[](t), i = 0;
  int[char] d;
  foreach (ai; a)
    foreach (aij; ai) {
      d[aij] = i;
      c[i++] = aij;
    }

  auto g = Graph!int(t);

  foreach (ai; a)
    foreach (j; 0..ai.length-1)
      g.addEdge(d[ai[j]], d[ai[j+1]]);
  foreach (bi; b)
    foreach (j; 0..bi.length-1)
      g.addEdge(d[bi[j]], d[bi[j+1]]);

  if (g.count!(gi => gi.empty) > 1) {
    writeln(-1);
    return;
  }

  auto ts = g.topologicalSort;
  foreach (ti; ts) write(c[ti]);
  writeln;
}

struct Graph(N = int)
{
  alias Node = N;
  Node n;
  Node[][] g;
  alias g this;
  this(Node n) { this.n = n; g = new Node[][](n); }
  void addEdge(Node u, Node v) { g[u] ~= v; }
  void addEdgeB(Node u, Node v) { g[u] ~= v; g[v] ~= u; }
}

auto topologicalSort(Graph)(ref Graph g)
{
  import std.container;
  alias Node = g.Node;
  auto n = cast(Node)(g.length), h = new int[](n);

  foreach (u; 0..n)
    foreach (v; g[u])
      ++h[v];

  auto st = SList!Node();
  foreach (i; 0..n)
    if (h[i] == 0) st.insertFront(i);

  Node[] ans;
  while (!st.empty()) {
    auto u = st.front; st.removeFront();
    ans ~= u;
    foreach (v; g[u]) {
      --h[v];
      if (h[v] == 0) st.insertFront(v);
    }
  }

  return ans;
}
0