/* * Solution to "Decompressing a GIF" */ import java.util.*; class Pair { public int index; public String entry; public Pair(int i, String s) { index = i; entry = s; } } public class Gif { public static String s; public static int n; public static String alph[]; public static int maxLength; public static int caseNum; public static Scanner in; public static ArrayList strings; public static ArrayList codes; public static String decoded; public static void main(String[] args) { caseNum = 0; in = new Scanner(System.in); while(true) { s = in.next(); if (s.equals("0")) break; caseNum++; n = in.nextInt(); alph = new String[n]; for (int i = 0; i < n; i++) alph[i] = in.next(); if (n <= 10) maxLength = 1; else maxLength = 2; System.out.println("Case " + caseNum + ": " + solve()); } } public static String solve() { strings = new ArrayList(); codes = new ArrayList(); for (int i = 0; i < n; i++) { insert(new Pair(i,alph[i])); codes.add(new Pair(i,alph[i])); } int pos = 0; String result = ""; while (pos < s.length()) { if (pos + maxLength > s.length()) return "Error in decompression"; int code = Integer.parseInt(s.substring(pos,pos+maxLength)); pos += maxLength; result += codes.get(code).entry; if (pos < s.length()) { maxLength = (""+n).length(); if (pos+maxLength > s.length()) return("Error in decompression"); int nextCode = Integer.parseInt(s.substring(pos,pos+maxLength)); char nextLetter; if (nextCode == n) nextLetter = codes.get(code).entry.charAt(0); else nextLetter = codes.get(nextCode).entry.charAt(0); insert(new Pair(n,codes.get(code).entry + nextLetter)); codes.add(new Pair(n,codes.get(code).entry + nextLetter)); n++; } } return result; } public static void insert(Pair p) { int i = 0; while (i < strings.size()) { Pair q = strings.get(i); if (p.entry.compareTo(q.entry) <= 0) { break; } i++; } strings.add(i,p); } }