BZOJ 4098: [Usaco2015 Open]Palindromic Paths
暴力的想法是设五维数组进行DP
但是发现如果知道纵坐标及步数就能知道横坐标
那么就是需要三维
再把步数进行滚动即可
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define pii pair<int, int>
#define pli pair<ll, int>
#define SZ(x) ((int)(x).size())
#define lp p << 1
#define rp p << 1 | 1
#define mid ((l + r) / 2)
#define lowbit(i) ((i) & (-i))
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=((b)-1);i>=(a);i--)
#define Edg int ccnt=1,head[N],to[E],ne[E];void addd(int u,int v){to[++ccnt]=v;ne[ccnt]=head[u];head[u]=ccnt;}void add(int u,int v){addd(u,v);addd(v,u);}
#define Edgc int ccnt=1,head[N],to[E],ne[E],c[E];void addd(int u,int v,int w){to[++ccnt]=v;ne[ccnt]=head[u];c[ccnt]=w;head[u]=ccnt;}void add(int u,int v,int w){addd(u,v,w);addd(v,u,w);}
#define es(u,i,v) for(int i=head[u],v=to[i];i;i=ne[i],v=to[i])
const int MOD = 1000000007;
void M(int &x) {if (x >= MOD)x -= MOD; if (x < 0)x += MOD;}
int qp(int a, int b = MOD - 2) {int ans = 1; for (; b; a = 1LL * a * a % MOD, b >>= 1)if (b & 1)ans = 1LL * ans * a % MOD; return ans % MOD;}
template<class T>T gcd(T a, T b) { while (b) { a %= b; std::swap(a, b); } return a; }
template<class T>bool chkmin(T &a, T b) { return a > b ? a = b, 1 : 0; }
template<class T>bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
char buf[1 << 21], *p1 = buf, *p2 = buf;
inline char getc() {
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++;
}
inline int _() {
int x = 0, f = 1; char ch = getc();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getc(); }
while (ch >= '0' && ch <= '9') { x = x * 10ll + ch - 48; ch = getc(); }
return x * f;
}
const int N = 555;
int f[N][N];
char s[N][N];
int n;
int main() {
#ifdef LOCAL
freopen("ans.out", "w", stdout);
#endif
scanf("%d", &n);
rep (i, 1, n + 1) scanf("%s", s[i] + 1);
if (s[1][1] != s[n][n]) return puts("0"), 0;
f[1][n] = 1;
rep (k, 1, n) {
per (x1, 1, k + 2) {
rep (x2, n - k, n + 1) {
int y1 = k + 2 - x1, y2 = 2 * n - x2 - k;
if (s[x1][y1] == s[x2][y2]) {
M(f[x1][x2] += f[x1 - 1][x2]);
M(f[x1][x2] += f[x1][x2 + 1]);
M(f[x1][x2] += f[x1 - 1][x2 + 1]);
} else {
f[x1][x2] = 0;
}
}
}
}
int ans = 0;
rep (i, 1, n + 1) M(ans += f[i][i]);
printf("%d\n", ans);
#ifdef LOCAL
printf("%.10f\n", (db)clock() / CLOCKS_PER_SEC);
#endif
return 0;
}