虚拟两个点,一个从左上角开始走,一个从右下角开始走,定义dp[i][j][k]表示走了i步后,第一个点横向走了j步,第二个点横向走了k步后形成的回文方法种数。
转移方程显然可得,然后滚动数组搞一搞。
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <bitset> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi acos(-1.0) # define eps 1e-8 # define MOD 1000000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FDR(i,a,n) for(int i=a; i>=n; --i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; inline int Scan() { int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();} return x*f; } inline void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=505; //Code begin... int dp[2][N][N]; char s[N][N]; int main () { int n=Scan(), m=Scan(), num=(n+m-2), flag=0; FOR(i,1,n) scanf("%s",s[i]+1); dp[flag][0][0]=1; FOR(i,0,num/2-1) { flag^=1; mem(dp[flag],0); FOR(j,0,min(i,m-1)) FOR(k,0,min(i,m-1)) { if (s[i-j+1][j+1]!=s[n-i+k][m-k]) continue; int tmp=dp[flag^1][j][k]; if (j+1<m && m-k>1 && s[i-j+1][j+2]==s[n-i+k][m-k-1]) dp[flag][j+1][k+1]=(dp[flag][j+1][k+1]+tmp)%MOD; if (j+1<m && n-i+k>1 && s[i-j+1][j+2]==s[n-i+k-1][m-k]) dp[flag][j+1][k]=(dp[flag][j+1][k]+tmp)%MOD; if (i-j+1<n && m-k>1 && s[i-j+2][j+1]==s[n-i+k][m-k-1]) dp[flag][j][k+1]=(dp[flag][j][k+1]+tmp)%MOD; if (i-j+1<n && n-i+k>1 && s[i-j+2][j+1]==s[n-i+k-1][m-k]) dp[flag][j][k]=(dp[flag][j][k]+tmp)%MOD; } } int ans=0; if (num&1) FOR(j,0,min(num/2,m-1)) ans=(ans+dp[flag][j][m-2-j])%MOD, ans=(ans+dp[flag][j][num/2*2-n-j+2]); else FOR(j,0,min(num/2,m-1)) ans=(ans+dp[flag][j][m-1-j])%MOD; printf("%d ",ans); return 0; }