1027. 方格取数(数字三角模型)

 

#include <bits/stdc++.h>

using namespace std;

const int N = 15;
int w[N][N], f[2*N][N][N];
int n, a, b, c;

int main() {
    scanf("%d",&n);
    
    while(cin >> a >> b >> c, a || b || c) w[a][b] = c;
    // f[k][x1][x2] 表示当前路径长度为k 且第一条路径横坐标为x1第二题路径横坐标为x2的最大和
    for(int k = 1; k < 2*n; k++) {
        for(int x1 = 1; x1 <= min(k,n); x1++) {
            for(int x2 = 1; x2 <= min(k,n); x2++) {
                int y1 = k + 1 - x1, y2 = k + 1 -x2;
                if(x1 == x2) {
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1][x2] + w[x1][y1]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1-1][x2-1] + w[x1][y1]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1][x2-1] + w[x1][y1]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1-1][x2] + w[x1][y1]);
                } else {
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1][x2] + w[x1][y1] + w[x2][y2]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1-1][x2-1] + w[x1][y1] + w[x2][y2]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1-1][x2] + w[x1][y1] + w[x2][y2]);
                    f[k][x1][x2] = max(f[k][x1][x2],f[k-1][x1][x2-1] + w[x1][y1] + w[x2][y2]);
                }
                
            }
        }
    }
    printf("%d\n",f[2*n-1][n][n]);
    return 0;
}

 二维dp:

#include <bits/stdc++.h>

using namespace std;

const int N = 15;
int w[N][N], f[N][N];
int n, a, b, c;

int main() {
    scanf("%d",&n);
    
    while(cin >> a >> b >> c, a || b || c) w[a][b] = c;

    for(int k = 1; k < 2*n; k++) {
        for(int x1 = min(k,n); x1 > 0; x1--) {
            for(int x2 = min(k,n); x2 > 0; x2--) {
                int y1 = k + 1 - x1, y2 = k + 1 -x2;
                int t = x1 == x2 ? w[x1][y1] : (w[x2][y2] + w[x1][y1]);
                f[x1][x2] = max(f[x1][x2],max(f[x1-1][x2-1],max(f[x1-1][x2],f[x1][x2-1]))) + t;
            }
        }
    }
    printf("%d\n",f[n][n]);
    return 0;
}

 

posted @ 2020-09-04 11:00  Sexyomaru  阅读(170)  评论(0编辑  收藏  举报