結果

問題 No.470 Inverse S+T Problem
コンテスト
ユーザー tiger2005
提出日時 2026-07-03 17:12:19
言語 C++23
(gcc 15.2.0 + boost 1.90.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,860 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,384 ms
コンパイル使用メモリ 338,360 KB
実行使用メモリ 6,528 KB
最終ジャッジ日時 2026-07-03 17:13:37
合計ジャッジ時間 3,866 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;

using i64 = long long;

char U[53][5];
string str[53][2][2];

vector<int> g[110];
int dfn[110], low[110], idx;
vector<int> stk;
bool instk[110];
int scc[110], sccid;

void tarjan(int x) {
  dfn[x] = low[x] = ++ idx;
  stk.push_back(x);
  instk[x] = true;
  for (auto v : g[x]) {
    if (!dfn[v]) {
      tarjan(v);
      low[x] = min(low[x], low[v]);
    } else if (instk[v]) {
      low[x] = min(low[x], dfn[v]);
    }
  }

  if (low[x] == dfn[x]) {
    ++ sccid;
    int cur = 0;
    while (cur != x) {
      cur = stk.back();
      stk.pop_back();
      instk[cur] = false;
      scc[cur] = sccid;
    }
  }
}

int main() {
  int n;
  scanf("%d", &n);
  if (n > 52) {
    puts("Impossible");
    return 0;
  }

  for (int i = 1; i <= n; i ++) {
    scanf(" %s", U[i]);
    str[i][0][0] = U[i][0];
    str[i][0][1] = string(1, U[i][1]) + U[i][2];
    str[i][1][0] = U[i][2];
    str[i][1][1] = string(1, U[i][0]) + U[i][1];
  }

  for (int i = 1; i <= n; i ++) {
    for (int j = 1; j < i; j ++) {
      for (int c = 0; c < 2; c ++) {
        for (int d = 0; d < 2; d ++) {
          if (str[i][c][0] == str[j][d][0] || str[i][c][1] == str[j][d][1]) {
            int posx = i + c * n, posy = j + d * n;
            int negx = i + (!c) * n, negy = j + (!d) * n;
            g[posx].push_back(negy);
            g[posy].push_back(negx);
          }
        }
      }
    }
  }

  for (int i = 1; i <= 2 * n; i ++)
    if (!dfn[i]) tarjan(i);

  for (int i = 1; i <= n; i ++) {
    if (scc[i] == scc[i + n]) {
      puts("Impossible");
      return 0;
    }
  }

  for (int i = 1; i <= n; i ++) {
    int chosen = (scc[i] < scc[i + n]) ? 0 : 1;
    if (chosen == 0) {
      printf("%c %c%c\n", U[i][0], U[i][1], U[i][2]);
    } else {
      printf("%c%c %c\n", U[i][0], U[i][1], U[i][2]);
    }
  }

  return 0;
}
0