http://acm.hdu.edu.cn/showproblem.php?pid=3658
Description
In order to make a new word, we will pick out m letters from all the upper case letters and lower case letters(from a' to
Z’). Therefore, that means you can pick some same letters. But here are two rules:
● as to all the neighbour letters, the absolute value of their ASCII code must be not greater than 32.
● there must be at least one pair of neighbour letters whose absolute value of ASCII code is exactly equal to 32. For example, considering the word in the form like “Xx” or “xX”, the neighbour letters have an absolute value of ASCII code exactly equal to 32.
Now how many dierent words can we get?
Input
The first line of input is the number of test case. For each test case, there is only one line contains one integer m(2 ≤ m ≤ 10 9).
Output
For each test case output one line, just the answer mod 1000000007.
Sample Input
4
2
3
100
7926778
Sample Output
52
4056
533550434
773908369
题意:一个长度为m的字符串需要填充,填充字母必须是’A’ ~ ‘Z’,’a’ ~ ‘z’,要求字符串相邻字符的ASCII值的差值≤32,且必须至少存在一个相邻字符差值等于32。问有多少种填充方式。
思路:直接构造至少存在一个相邻字符差值等于32的不好做,可以先求出差值小于等于32的总数,再求出差值小于等于31的总数,两者相减即为结果。假设f(n)(j)表示的是前n个字符最后一个字符为j,
对于“相邻的两个字符的ASCII码的绝对值小于等于32”,f(n)(j) = Σ(f(n-1)(k)) , abs(j-k) <= 32,于是可以矩阵进行求解。
代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int MOD=1000000007;
typedef __int64 ll;
struct matrix
{
ll a[52][52];
};
matrix A,B;
void init()
{
for(int i=0; i<52; i++)
F[i]=52;
memset(A.a,0,sizeof A.a);
int num=27;
for(int i=0; i<26; i++)
{
for(int j=0; j<num; j++)
A.a[i][j]=1;
num++;
}
//printf("num=%d\n",num);
num--;
for(int i=26; i<52; i++)
{
for(int j=51; j>=52-num; j--)
A.a[i][j]=1;
num--;
}
memset(B.a,0,sizeof B.a);
num=26;
for(int i=0; i<26; i++)
{
for(int j=0; j<num; j++)
B.a[i][j]=1;
num++;
}
num--;
for(int i=26; i<52; i++)
{
for(int j=51; j>=52-num; j--)
B.a[i][j]=1;
num--;
}
}
matrix Mul(matrix A,matrix B)
{
matrix res;
memset(res.a,0,sizeof res.a);
for(int i=0; i<52; i++)
for(int j=0; j<52; j++)
for(int k=0; k<52; k++)
{
res.a[i][j]=(res.a[i][j]+A.a[i][k]%MOD*B.a[k][j]%MOD)%MOD;
}
return res;
}
matrix Poww(matrix A,int n)
{
matrix res;
memset(res.a,0,sizeof res.a);
for(int i=0; i<52; i++)
res.a[i][i]=1;
while(n)
{
if(n&1)
res=Mul(res,A);
A=Mul(A,A);
n>>=1;
}
return res;
}
int main()
{
init();
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
matrix Ans1=Poww(A,n-1);
matrix Ans2=Poww(B,n-1);
ll sum1=0,sum2=0;
for(int i=0; i<52; i++)
{
for(int j=0; j<52; j++)
{
sum1=(sum1+Ans1.a[i][j])%MOD;
sum2=(sum2+Ans2.a[i][j])%MOD;
}
}
//printf("%I64d %I64d\n",sum1,sum2);
printf("%I64d\n",(sum1+MOD-sum2)%MOD);
}
return 0;
}