比赛时没写出来,结束后听ccx学长讲,才知道有多线程DP,感觉自己菜成dog,之前就没听过,还是太弱。
dp:
#include <iostream> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <stack> using namespace std; int dp[222][111][111]; int a[111][111]; #define max4(a,b,c,d) max(max(a,b),max(c,d)) int main() { int t, n, m; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) scanf("%d", &a[i][j]); } memset(dp, 0, sizeof(dp)); dp[0][1][1] = a[1][1]; for(int k=1; k<=n+m-2; k++) { for(int i=1; i<=k+1; i++) { for(int j=1; j<=k+1; j++) { dp[k][i][j] = max4(dp[k-1][i][j], dp[k-1][i-1][j], dp[k-1][i][j-1], dp[k-1][i-1][j-1]); if(i!=j) dp[k][i][j]+=a[i][k+2-i]+a[j][k+2-j]; else dp[k][i][j]+=a[i][k+2-i]; } } } printf("%d ", dp[n+m-2][n][n]); } return 0; }
记忆化搜索
#include <iostream> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <stack> using namespace std; int dp[222][111][111]; int a[111][111]; #define max4(a,b,c,d) max(max(a,b),max(c,d)) int DFS(int k, int i1, int i2) { if(dp[k][i1][i2]) return dp[k][i1][i2]; if(k==0||i1==0||i2==0||k+2-i1==0||k+2-i2==0) return dp[k][i1][i2]; dp[k][i1][i2] = max4(DFS(k-1, i1-1, i2), DFS(k-1, i1, i2-1), DFS(k-1, i1-1, i2-1), DFS(k-1, i1, i2)); if(i1!=i2) dp[k][i1][i2] += a[i1][k+2-i1]+a[i2][k+2-i2]; else dp[k][i1][i2] += a[i1][k+2-i1]; return dp[k][i1][i2]; } int main() { int t, n, m; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &m); for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) scanf("%d", &a[i][j]); } memset(dp, 0, sizeof(dp)); dp[0][1][1] = a[1][1]; int ans = DFS(n+m-2, n, n); printf("%d ", ans); } return 0; }