https://www.acmicpc.net/problem/8111
X, Y 값이 (X mod N) = (Y mod N)을 만족할 때
(X x 10 + 1) mod N = (Y x 10 + 1) mod N
(X x 10) mod N = (Y x 10) mod N
이라는 식이 성립하게 된다 따라서 bfs 진행 중 X, Y 중 하나는 가지치기가 가능하다.
import java.io.*;
import java.util.*;
public class Main {
public static BufferedReader br;
public static BufferedWriter bw;
public static int T, N;
public static class Point {
String str;
int num;
public Point(String str, int num) {
this.str = str;
this.num = num;
}
}
public static String solve() {
boolean[] chk = new boolean[N+1];
Queue<Point> q = new ArrayDeque<>();
//뺴도 될지 확인
if (N == 1) return "1";
chk[1] = true;
q.add(new Point("1", 1));
while(!q.isEmpty()) {
Point cur = q.poll();
if (cur.num == 0) return cur.str;
int nextNum;
// 0붙이기
nextNum = cur.num * 10;
nextNum = nextNum % N;
if (!chk[nextNum]) {
chk[nextNum] = true;
q.add(new Point(cur.str.concat("0"), nextNum));
}
// 1붙이기
nextNum = cur.num * 10 + 1;
nextNum = nextNum % N;
if (!chk[nextNum]) {
chk[nextNum] = true;
q.add(new Point(cur.str.concat("1"), nextNum));
}
}
return "BRAK";
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
N = Integer.parseInt(br.readLine());
bw.write(solve() + "\n");
}
bw.flush();
bw.close();
bw.close();
}
}