[Question link]
Https://www.lydsy.com/JudgeOnline/problem.php? Id = 4098
[Algorithm]
Obviously, the position (x, y) of the I-th letter in the return path must meet the following requirements: X + Y-1 = I
Use F [I] [J] [k] to represent the current step I. The upper left X axis is J, and the lower right X axis is K, how many solutions are there to make the letter sequence on both paths the same, DP is enough
Time Complexity: O (N ^ 3)
Scroll array to optimize the space complexity to O (N ^ 2)
[Code]
#include<bits/stdc++.h>using namespace std;#define MAXN 510 const int P = 1e9 + 7;int n;int f[2][MAXN][MAXN];char mp[MAXN][MAXN];inline void update(int &x , int y){ x += y; x %= P;}inline bool valid(int x , int y){ return x >= 1 && x <= n && y >= 1 && y <= n;}int main(){ scanf("%d",&n); for (int i = 1; i <= n; i++) scanf("%s",mp[i] + 1); if (mp[1][1] == mp[n][n]) { f[1][1][n] = 1; } else { printf("0\n"); return 0; } for (int i = 1; i <= n; i++) { int now = i & 1 , nxt = now ^ 1; memset(f[nxt] , 0 , sizeof(f[nxt])); for (int x = 1; x <= n; x++) { for (int y = 1; y <= n; y++) { int t1 = i + 1 - x , t2 = 2 * n - y + 1 - i; if (!valid(x , t1) || !valid(y , t2)) continue; if (!f[now][x][y]) continue; if (valid(x , t1 + 1)) { if (valid(y , t2 - 1) && mp[x][t1 + 1] == mp[y][t2 - 1]) update(f[nxt][x][y] , f[now][x][y]); if (valid(y - 1 , t2) && mp[x][t1 + 1] == mp[y - 1][t2]) update(f[nxt][x][y - 1] , f[now][x][y]); } if (valid(x + 1 , t1)) { if (valid(y , t2 - 1) && mp[x + 1][t1] == mp[y][t2 - 1]) update(f[nxt][x + 1][y] , f[now][x][y]); if (valid(y - 1 , t2) && mp[x + 1][t1] == mp[y - 1][t2]) update(f[nxt][x + 1][y - 1] , f[now][x][y]); } } } } int ans = 0; for (int i = 1; i <= n; i++) update(ans , f[n & 1][i][i]); printf("%d\n" , ans); return 0; }
[Usaco 2015 open] palindromic paths