设f[i][j][k][l]为从小渊传到小轩的纸条到达(i,j),从小轩传给小渊的纸条到达(k,l)的路径上取得的最大的好心程度和。
f[i][j][k][l]=max( f[i][j-1][k-1][l] , f[i-1][j][k][l-1] , f[i][j-1][k][l-1] , f[i-1][j][k-1][l] )+a[i][j]+a[k][l]。
当i==k&&j==l时,f[i][j][k][l]-=a[i][j];
升级算法:
对于每次转移,这两位同学的纸条走的步数总是相等的,也就是应该总有i+j = k+l = step
同时枚举第一个人和第二个人的横坐标或者纵坐标,另一个可以靠步数-坐标算出来。
f[k][i][j] = max(f[k-1][i][j],f[k-1][i-1][j-1],f[k-1][i][j-1],f[k-1][i-1][j]) + a[i][k-i+1] + a[j][k-j+1];
#include <bits/stdc++.h> #define cin std::ios::sync_with_stdio(false); cin #define cout std::ios::sync_with_stdio(false); cout using namespace std; int mmap[50][50]; int f[100][100][100]; int main() { int n; cin>>n; while(1){ int a,b,c; cin>>a>>b>>c; if(a==b&&b==c&&a==0){ break; } mmap[a][b]=c; } for(register int k=1;k<=2*n-1;k++){ for(register int i=1;i<=n;i++){ for(register int j=1;j<=n;j++){ f[k][i][j]=max(f[k-1][i][j],max(f[k-1][i-1][j],max(f[k-1][i][j-1],f[k-1][i-1][j-1])))+mmap[i][k-i+1]+mmap[j][k-j+1]; if(i==j) f[k][i][j]-=mmap[i][k-i+1]; } } } cout<<f[2*n-1][n][n]; }