From 3731f28acc2e2b7dd40a29a4e917c9141338773b Mon Sep 17 00:00:00 2001 From: HeeEul Shin <83682424+ShinHeeEul@users.noreply.github.com> Date: Wed, 5 Feb 2025 22:13:55 +0900 Subject: [PATCH] =?UTF-8?q?[20250205]=20BOJ=20/=20P4=20/=20=EC=8B=9C?= =?UTF-8?q?=EC=A0=80=20=EC=95=94=ED=98=B8=20/=20=EC=8B=A0=ED=9D=AC?= =?UTF-8?q?=EC=9D=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...4\354\240\200 \354\225\224\355\230\270.md" | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 "ShinHeeEul/202502/05 BOJ P4 \354\213\234\354\240\200 \354\225\224\355\230\270.md" diff --git "a/ShinHeeEul/202502/05 BOJ P4 \354\213\234\354\240\200 \354\225\224\355\230\270.md" "b/ShinHeeEul/202502/05 BOJ P4 \354\213\234\354\240\200 \354\225\224\355\230\270.md" new file mode 100644 index 00000000..53ded0bd --- /dev/null +++ "b/ShinHeeEul/202502/05 BOJ P4 \354\213\234\354\240\200 \354\225\224\355\230\270.md" @@ -0,0 +1,96 @@ +```java +import java.util.*; +import java.io.*; + +public class Main { + + static int[] failure; + public static void main(String[] args) throws IOException { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int T = Integer.parseInt(br.readLine()); + + StringBuilder sb = new StringBuilder(); + + while(T --> 0) { + ArrayList list = new ArrayList<>(); + HashMap map = new HashMap<>(); + + char[] A = br.readLine().toCharArray(); + char[] W = br.readLine().toCharArray(); + char[] S = br.readLine().toCharArray(); + int aLength = A.length; + for(int i = 0; i < aLength; i++) { + map.put(A[i], i); + } + failure = new int[W.length]; + + failureFunction(W); + + for(int i = 0; i < aLength; i++) { + if(i != 0) { + for(int j = 0; j < S.length; j++) { + S[j] = A[(map.get(S[j]) + 1) % aLength]; + } + } + + if(kmp(S, W)) { + list.add(i == 0 ? i : aLength - i); + } + } + if(list.size() == 0) { + sb.append("no solution").append("\n"); + } else if(list.size() == 1) { + sb.append("unique: ").append(list.get(0)).append("\n"); + } else { + Collections.sort(list); + sb.append("ambiguous: "); + for(int li : list) sb.append(li).append(" "); + sb.append("\n"); + } + } + System.out.println(sb); + } + + public static void failureFunction(char[] pattern) { + + int pIdx = 0; + + for(int i = 1; i < pattern.length; i++) { + + while(pIdx != 0 && pattern[pIdx] != pattern[i]) + pIdx = failure[pIdx - 1]; + + if(pattern[pIdx] == pattern[i]) { + failure[i] = ++pIdx; + } + } + } + + public static boolean kmp(char[] s, char[] pattern) { + int pIdx = 0; + int max = 0; + // ABCBBABC + // ABC + // + for(int i = 0; i < s.length; i++) { + + while(pIdx != 0 && pattern[pIdx] != s[i]) + pIdx = failure[pIdx - 1]; + + if(pattern[pIdx] == s[i]) { + if(pIdx == pattern.length - 1) { + max++; + pIdx = failure[pIdx]; + } else { + pIdx++; + } + } + } + + return max == 1; + } + +} +```