方格取数(dp)

方格取数(dp)_第1张图片
方格取数(dp)_第2张图片
方格取数(dp)_第3张图片

思路:数字三角形模型拓展以下我们用dp[i1][j1][i2][j2]表示两个路径从(1,1)点出发到(i1,j1),(i2,j2)。我们可以发现是同时出发所以i1+j1= i2+j2 所以我们可以压缩一维令 k=i1+j1,那么就变成了dp[k][i1][i2]此时我们令x=dp[k][i1][i2],同时走有四个状态:

1.a向下b向下 x = m a x ( x , d p [ k − 1 ] [ i 1 ] [ i 2 ] + w ) x=max(x,dp[k-1][i1][i2]+w) x=max(x,dp[k1][i1][i2]+w)

2.a向右b向右 x = m a x ( x , d p [ k − 1 ] [ i 1 − 1 ] [ i 2 − 1 ] + w ) x=max(x,dp[k-1][i1-1][i2-1]+w) x=max(x,dp[k1][i11][i21]+w)

3.a向右b向下 x = m a x ( x , d p [ k − 1 ] [ i 1 ] [ i 2 − 1 ] + w ) x=max(x,dp[k-1][i1][i2-1]+w) x=max(x,dp[k1][i1][i21]+w)

4.a向下b向右 x = m a x ( x , d p [ k − 1 ] [ i 1 − 1 ] [ i 2 ] + w ) x=max(x,dp[k-1][i1-1][i2]+w) x=max(x,dp[k1][i11][i2]+w)

我们判断一下此时的i1,j1和i2,j2是否相同若相同则w=val[i1][j1]若不同w=val[i1][j1]+val[i2][j2]

#include 
#include 
#include 
#include 
#include
#include
#include
#include
//#include
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=100000000;
const int N=2e6+10;
const int M=1e3+10;
const int inf=0x7f7f7f7f;
const int maxx=2e5+7;

ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    ll res=1%p;
    while(b)
    {
        if(b&1) res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
struct node
{
    int to,nex;
}edge[N];

int dp[100][100][100];
int w[100][100];
int main()
{
    SIS;
    int n;
    cin>>n;
    int a,b,c;
    while(cin>>a>>b>>c,a||b||c)
        w[a][b]=c;

   for(int k=2;k<=n*2;k++)
    for(int i1=1;i1<=n;i1++)
     for(int i2=1;i2<=n;i2++)
   {
       int j1=k-i1,j2=k-i2;
       if(j1>=1&&j1<=n&&j2>=1&&j2<=n)
       {
           int t=w[i1][j1];
           if(i1!=i2) t+=w[i2][j2];
           int &x=dp[k][i1][i2];
           x=max(x,dp[k-1][i1][i2]+t);
           x=max(x,dp[k-1][i1-1][i2-1]+t);
           x=max(x,dp[k-1][i1-1][i2]+t);
           x=max(x,dp[k-1][i1][i2-1]+t);

       }
   }
   cout<<dp[n*2][n][n];


    return 0;
}

你可能感兴趣的:(DP)