結果

問題 No.517 壊れたアクセサリー
ユーザー tenten
提出日時 2020-12-10 16:45:32
言語 Java
(openjdk 23)
結果
AC  
実行時間 127 ms / 2,000 ms
コード長 1,745 bytes
コンパイル時間 2,982 ms
コンパイル使用メモリ 79,192 KB
実行使用メモリ 54,440 KB
最終ジャッジ日時 2024-09-19 20:37:55
合計ジャッジ時間 5,189 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 15
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        HashSet<Integer> starts = new HashSet<>();
        int[] next = new int[26];
        Arrays.fill(next, -1);
        boolean[] used = new boolean[26];
        for (int i = 0; i < n; i++) {
            char[] arr = sc.next().toCharArray();
            starts.add(arr[0] - 'A');
            used[arr[0] - 'A'] = true;
            for (int j = 0; j < arr.length - 1; j++) {
                next[arr[j] - 'A'] = arr[j + 1] - 'A';
                used[arr[j + 1] - 'A'] = true;
            }
        }
        int count = 0;
        for (boolean b : used) {
            if (b) {
                count++;
            }
        }
        int m = sc.nextInt();
        for (int i = 0; i < m; i++) {
            char[] arr = sc.next().toCharArray();
            starts.add(arr[0] - 'A');
            for (int j = 0; j < arr.length - 1; j++) {
                if (next[arr[j] - 'A'] >= 0 && next[arr[j] - 'A'] != arr[j + 1] - 'A') {
                    System.out.println(-1);
                    return;
                }
                next[arr[j] - 'A'] = arr[j + 1] - 'A';
            }
        }
        for (int x : starts) {
            int cur = x;
            int c = 0;
            StringBuilder sb = new StringBuilder();
            sb.append((char)(cur + 'A'));
            while (next[cur] >= 0) {
                cur = next[cur];
                sb.append((char)(cur + 'A'));
                c++;
            }
            if (c == count - 1) {
                System.out.println(sb);
                return;
            }
        }
        System.out.println(-1);
    }
}
0