B2. Palindrome Game (hard version)
题意
给定一个字符串(只包含0和1),ALICE和BOB轮流操作,当字符串全为1时,游戏结束
- 操作1: 将其中的一个0换成1,代价为1
- 操作2:反转字符串,前提是当前字符串不是一个回文串,并且上一个人的操作不是反转字符串
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B2 {
private int n;
private String s;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
B2 b2 = new B2();
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int i = 0; i < t; i++) {
b2.read();
b2.solve();
}
}
// 3
// 110
// ALICE
// 2
// 00
// BOB
// 4
// 1010
// ALICE
private void solve() {
int cnt = 0;
for(int i = 0; i < n; i++) {
if(s.charAt(i) == '0') {
cnt++;
}
}
if(check()) {
// 如果是回文串
if((cnt & 1) == 1 && cnt > 1) System.out.println("ALICE");
else System.out.println("BOB");
} else {
// 如果不是回文串
// 如果0的个数为2个,并且n为奇数,中间的字符为0,导致了反转一次可以变成回文串
// 10110
// 10011
// 这样的话ALICE和BOB各pay 1
if(cnt == 2 && s.charAt(s.length() / 2) == '0' && s.length() % 2 == 1) {
System.out.println("DRAW");
} else {
// 如果可以将字符串变成回文串
// cnt:偶数 ALICE 选择反转,让BOB执行这一步
// cnt:奇数 ALICE 执行操作一,类似于之前一开始就是回文串且cnt为奇数的情况相同
System.out.println("ALICE");
}
}
}
private Boolean check() {
for(int i = 0; i < n / 2; i++) {
if(s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
private void read() throws IOException {
n = Integer.parseInt(br.readLine());
s = br.readLine();
}
}