B. Word Cut
http://codeforces.com/contest/176/problem/B
题意:
给定a串和b串,要求切k次,每次切完将尾部分放在头的前面(a = xy -> yx ,x、y为a的子串),问有多少种方案使得切k次后a串变为b串。[模:1000000007 (109 + 7)]
数据:
(0 ≤ k ≤ 105) (la,lb≤1000 )
思路:
1. 可以把串看做一个环,那么每次切的操作则相当于只是旋转了串。
2. 那么相当于a环每次必须旋转,求k次后有多少种方案变成b环。
3. 那么 DP 或者 直接算 。
4. DP每次只有两类变化:
(l-1)种从 a串 变成 其它串;
(l-2)种从 其它串 变成 其它串 + 1种从 a串 变成 其它串;
即:
dp[i%2][0]=(l-1)*dp[(i+1)%2][1];
dp[i%2][1]=(l-2)*dp[(i+1)%2][1] + dp[(i+1)%2][0] ;
5. 最后累加 b串 所有循环后满足的情况。
代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 2007;
const int M = 100005;
const int INF = 100000001;
const int MOD = 1000000007;
int n,m;
char s[N],t[N];
char tmp[N];
LL dp[3][3];
int k;
int sa[N];
int main()
{
while (~scanf("%s%s",&s,&t))
{
scanf("%d",&k);
int l=strlen(s);
int pos=0;
for (int i=0;i<l;i++)
{
memset(tmp,0,sizeof(tmp));
for (int j=0;j<l;j++)
tmp[j]=t[(i+j)%l];
if (strcmp(s,tmp)==0)
sa[pos++]=i;
}
if (pos==0)
{
printf("0\n");
continue;
}
if (k==0)
{
if (sa[0]==0)
printf("1\n");
else
printf("0\n");
continue;
}
memset(dp,0,sizeof(dp));
dp[1][0]=0;
dp[1][1]=1;
for (int i=2;i<=k;i++)
{
dp[i%2][0]=((l-1)*dp[(i+1)%2][1] + MOD)%MOD;
dp[i%2][1]=(dp[(i+1)%2][0]+(l-2)*dp[(i+1)%2][1] + MOD)%MOD;
}
LL ans=0;
for (int i=0;i<pos;i++)
ans=(ans+dp[(k)%2][sa[i]==0?0:1])%MOD;
printf("%d\n",ans);
}
return 0;
}
/*
ab
ab
2
ababab
ababab
1
ab
ba
2
*/