백준 10942 팰린드롬
유형
- DP로 해결
- 재귀와 비재귀로 풀 수 있음 (주석 처리는 재귀 코드)
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class DP_Palindrome {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static boolean[][] dp;
static int[] num;
static int N;
public static void main(String[] args) throws NumberFormatException, IOException {
N = Integer.parseInt(br.readLine());
num = new int[N+1];
dp = new boolean[N+1][N+1];
StringTokenizer stz = new StringTokenizer(br.readLine());
for(int i = 1; i <= N; i++) {
num[i] = Integer.parseInt(stz.nextToken());
}
solve();
int M = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for(int i = 0; i < M; i++) {
stz = new StringTokenizer(br.readLine());
int S = Integer.parseInt(stz.nextToken());
int E = Integer.parseInt(stz.nextToken());
if(dp[S][E]) sb.append("1\n");
else sb.append("0\n");
}
System.out.println(sb);
}
public static void solve() {
for(int i = 1; i <= N; i++)
dp[i][i] = true;
for(int i = 1; i <= N - 1; i++)
if(num[i] == num[i + 1]) dp[i][i + 1]= true;
for(int i = 2; i < N; i++){
for(int j = 1; j <= N - i; j++){
if(num[j] == num[j + i] && dp[j + 1][j + i - 1])
dp[j][j + i] = true;
}
}
}
}