蓝桥杯——试题 算法训练 Sereja and Squares

时间:2023-03-10 07:23:49
蓝桥杯——试题 算法训练 Sereja and Squares

Java 代码

````

import java.util.Scanner;

public class Main {

private static long num = 0;

private static long mod = 4294967296L;

private static char[] arr = new char[100000 + 7];

private static long[] dp = new long[100000 + 7];

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
char[] tempChar = input.next().toCharArray();
for (int i = 0; i < tempChar.length; i++) {
arr[i + 1] = tempChar[i];
} // 没有右括号 ,这一步一定不能漏
dp[0] = 1;
long start = System.currentTimeMillis();
f(arr, n);
long end = System.currentTimeMillis();
System.out.println(num);
System.out.println(end - start + "ms");
} static void f(char[] arr, int n) {
if (n % 2 == 1) {
// 奇数直接返回
return;
} // 用来记录左括号的个数
int left = 0;
int n2 = n >> 1; // 循环从1~n
for (int i = 1; i <= n; i++) {
if (arr[i] == '?') {
// 若是问好,则可能是左括号也可能是右括号
// 确定右括号的最大上限
int rightMax = i >> 1;
if (i != n) {
/*
当dp到下标i时,可以确定的最多的右括号为i/2,
若现在确定的是左括号则前面i-1个格子就是确定rightMax个右括号的结果
若现在确定的是右括号,则前面i-1个格子确定的就是rightMax-1个右括号的结果
*/
// 因为只是确定了右括号的最大上限,而不确定到底是多少,所以有很多种可能
// 每次后面多来一个右括号的话,前面的可能性就越多
for (; rightMax >= 1; rightMax--) {
dp[rightMax] += dp[rightMax - 1];
dp[rightMax] %= mod;
}
} else {
//i==n一定是右括号,只要确定前n-1个格子所确定出来的n>>1-1个右括号的结果即可
dp[rightMax] = dp[rightMax - 1];
dp[rightMax] %= mod;
}
} else {
// 若不是问好,则一定是左括号
left++;
}
} if (left > n2) {
// 左括号的个数超过一半
return;
} for (int i = 0; i < n2 - left; i++) {
dp[n2] *= 25;
dp[n2] %= mod;
}
num = dp[n2] % mod;
}

}