考虑一个剪枝,当L + L >= n后,就可以直接用s[i]与s[n - L + i]来更新ans[i]了.
#include <iostream> #include <cstring> #include <cstdlib> #include <string> #include <cstdio> #include <algorithm> #include <cmath> #include <ctime> using namespace std; int queue[3010][3010],stack[3010],top = 0,num[3010]; int n,L,T,All; char Ans[3010],s[3010]; bool f[3010]; bool check(char x,char y) {return (x == y || x == '*' || y == '*');} bool dfs(int x) { if(queue[x][num[x]] < n - L + 1) return false; for(int i = 1;i < num[x];i ++) if(queue[x][i + 1] - queue[x][i] > L) return false; if(x == top) return true; Ans[stack[x + 1]] = 'R';num[x + 1] = 0; for(int i = 1;i <= num[x];i ++) if(check(s[queue[x][i] + stack[x + 1] - 1],'R')) queue[x + 1][ ++num[x + 1]] = queue[x][i]; if(dfs(x + 1)) return true; Ans[stack[x + 1]] = 'G';num[x + 1] = 0; for(int i = 1;i <= num[x];i ++) if(check(s[queue[x][i] + stack[x + 1] - 1],'G')) queue[x + 1][ ++num[x + 1]] = queue[x][i]; if(dfs(x + 1)) return true; Ans[stack[x + 1]] = 'B';num[x + 1] = 0; for(int i = 1;i <= num[x];i ++) if(check(s[queue[x][i] + stack[x + 1] - 1],'B')) queue[x + 1][ ++num[x + 1]] = queue[x][i]; return dfs(x + 1); } int main() { scanf("%d",&T); while(T --) { All = 0; bool rev = false; scanf("%s",s + 1); n = strlen(s + 1); for(int i = 1;i <= n;i ++) if(s[i] == '*') All ++; for(int i = 1;i <= n / 2;i ++) if(s[i] == '*') All -= 2; if(All < 0) reverse(s + 1,s + n + 1),rev = true; for(int i = 1;i <= n;i ++) f[i] = true,Ans[i] = s[i]; top = 0; for(L = 1;L <= n;L ++) { for(int i = 1;i <= n - L + 1;i ++) if(f[i] && check(s[L],s[i + L - 1]) == false) f[i] = 0; if(L + L >= n) { if(f[n - L + 1] == false) continue; for(int i = 1;i <= L;i ++) Ans[i] = s[i]; for(int i = 1;i <= L;i ++) if(s[i] == '*') Ans[i] = s[n - L + i]; break; } else { if(s[L] == '*') stack[ ++top] = L; num[0] = 0; for(int i = 1;i <= n - L + 1;i ++) if(f[i]) queue[0][ ++num[0]] = i; if(dfs(0)) break; } } if(rev == true) reverse(Ans + 1,Ans + L + 1); for(int i = 1;i <= L;i ++) printf("%c",((Ans[i] == '*') ? 'R' : Ans[i])); printf("\n"); } return 0; }