Problem Description
Beaver Bindu has N cupcakes. Each cupcake has one of three possible colors. In this problem we will represent the colors by uppercase letters \’A\’, \’B\’, and \’C\’. Two cupcakes of the same color are indistinguishable. You are given a String cupcakes consisting of exactly N characters. Each character in cupcakes gives the color of one of Bindu\’s cupcakes. Bindu has N friends, sitting around a round table. She wants to give each friend one of the cupcakes. Moreover, she does not want to give cupcakes of the same color to any pair of friends who sit next to each other. Let X be the number of ways in which she can hand out the cupcakes to her friends. As X can be very large, compute and return the value (X modulo 1, 000, 000, 007).
Input
The first line contains one integer T(1 ≤ T ≤ 60)—the number of test cases. Each of the next T lines contains one string. Each string will contain between 3 and 50 characters, inclusive. Each character in the string will be either \’A\’, \’B\’, or \’C\’.
Output
For each test case. Print a single number X — the number of ways in which she can hand out the cupcakes to her friends.
Example Input
3
ABAB
ABABA
ABABABABABABABABABABABABABABABABABABABABABABABABAB
Example Output
2
0
2
题目大意
有A,B,C三种颜色的蛋糕,然后分给围成一圈的朋友,要求相邻的两个人必须分到不同的颜色,问有多少种不同的分发。
解题思路
从后往前进行搜索,dp[i][a][b][k]代表前 i 个位置 A 有 a 个,B 有 b 个,且当前末尾位置的颜色为 k 。
代码实现
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 55
#define mod 1000000007
#define ll long long
int firstcolor,len;
int dp[maxn][maxn][maxn][3];
char str[maxn];
int countt[3];
int dfs(int length,int a,int b,int color) //a代表A的个数,b代表B的个数,length-a-b代表C的个数,color代表当前长度末尾的颜色
{
if((color==0&&a<=0)||(color==1&&b<=0)||(color==2&&length-a-b<=0)) return 0;
if(dp[length][a][b][color]!=-1) return dp[length][a][b][color];
if(length==0&&color==firstcolor) return 0; //当前为全分完,如果第一个颜色和最后一个颜色相同,直接返回0
if(length==0)
{
if((color==0&&a>0)||(color==1&&b>0)||(color==2&&length-a-b>0))
return 1;
else return 0;
}
int ans=0;
for(int ne=0;ne<3;ne++) //遍历上一个蛋糕的颜色
{
if(ne==color) continue;
if(color==0) ans=(ans+dfs(length-1,a-1,b,ne))%mod;
if(color==1) ans=(ans+dfs(length-1,a,b-1,ne))%mod;
if(color==2) ans=(ans+dfs(length-1,a,b,ne))%mod;
}
return dp[length][a][b][color]=ans;
}
int main()
{
int T;
scanf("%d%*c",&T);
while(T--)
{
int ans=0;
scanf("%s",str);
len=strlen(str);
memset(countt,0,sizeof(countt));
for(int i=0;i<len;i++)
countt[str[i]-'A']++;
for(int i=0;i<3;i++)
{
memset(dp,-1,sizeof(dp));
firstcolor=i; //标记下第一个蛋糕的颜色
ans=(ans+dfs(len,countt[0],countt[1],i))%mod;
}
printf("%d\n",ans);
}
return 0;
}