結果

問題 No.470 Inverse S+T Problem
ユーザー 37zigen37zigen
提出日時 2016-12-25 16:04:44
言語 Java
(openjdk 23)
結果
AC  
実行時間 190 ms / 2,000 ms
コード長 2,591 bytes
コンパイル時間 4,350 ms
コンパイル使用メモリ 81,208 KB
実行使用メモリ 43,688 KB
最終ジャッジ日時 2024-12-22 13:39:29
合計ジャッジ時間 9,642 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

package yukicoder;

import java.util.*;

public class Q470 {
	static ArrayList<Integer>[] g;

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		if (n > 52) {
			System.out.println("Impossible");
			return;
		}
		String[] u = new String[n];
		for (int i = 0; i < n; ++i) {
			u[i] = sc.next();
		}

		g = new ArrayList[2 * n];
		for (int i = 0; i < g.length; ++i) {
			g[i] = new ArrayList<>();
		}

		for (int i = 0; i < n; ++i) {
			for (int j = i + 1; j < n; ++j) {
				if (u[i].substring(0, 1).equals(u[j].substring(0, 1))
						|| u[i].substring(1, 3).equals(u[j].substring(1, 3))) {
					g[i].add(j + n);
					g[j].add(i + n);
				}
				if (u[i].substring(0, 1).equals(u[j].substring(2, 3))
						|| u[i].substring(1, 3).equals(u[j].substring(0, 2))) {
					g[i].add(j);
					g[n + j].add(n + i);
				}
				if (u[i].substring(0, 2).equals(u[j].substring(0, 2))
						|| u[i].substring(2, 3).equals(u[j].substring(2, 3))) {
					g[i + n].add(j);
					g[j + n].add(i);
				}
				if (u[i].substring(0, 2).equals(u[j].substring(1, 3))
						|| u[i].substring(2, 3).equals(u[j].substring(0, 1))) {
					g[i + n].add(j + n);
					g[j].add(i);
				}
			}
		}
		int V = 2 * n;
		vis = new boolean[V];
		marked = new boolean[V];
		cmp = new int[V];
		low = new int[V];
		id = new int[V];
		for (int i = 0; i < V; ++i) {
			if (!marked[i]) {
				dfs(i);
			}
		}
		for (int i = 0; i < n; ++i) {
			if (cmp[i] == cmp[i + n]) {
				System.out.println("Impossible");
				return;
			}
		}
		for (int i = 0; i < n; ++i) {
			if (cmp[i] < cmp[i + n]) {
				System.out.println(u[i].substring(0, 1) + " " + u[i].substring(1, 3));
			} else {
				System.out.println(u[i].substring(0, 2) + " " + u[i].substring(2, 3));
			}
		}
	}

	static ArrayDeque<Integer> stack = new ArrayDeque<>();
	static boolean[] vis;
	static int[] low;
	static int[] id;
	static int curId = 0;
	static boolean[] marked;
	static int[] cmp;
	static int col = 0;

	static void dfs(int cur) {
		vis[cur] = true;
		stack.addFirst(cur);
		id[cur] = curId++;
		low[cur] = id[cur];
		for (int dst : g[cur]) {
			if (marked[dst])
				continue;
			if (!vis[dst]) {
				dfs(dst);
				low[cur] = Math.min(low[cur], low[dst]);
			} else {
				low[cur] = Math.min(low[cur], id[dst]);
			}
		}
		if (id[cur] == low[cur]) {
			int v;
			do {
				v = stack.removeFirst();
				cmp[v] = col;
				marked[v] = true;
			} while (v != cur);
			++col;
		}
		return;
	}

	static void tr(Object... objects) {
		System.out.println(Arrays.deepToString(objects));
	}
}
0