题目链接:https://www.acwing.com/problem/content/277/
NOIP2008复赛提高组第三题,非常好的一个题,让我学会了很多东西
题意:
给定一个 的矩阵A,每个格子中有一个整数。
现在需要找到两条从左上角 到右下角
的路径,路径上的每一步只能向右或向下走。
路径经过的格子中的数会被取走,两条路径可以经过同一个格子,但格子中的数 只能被取一次。
求取得的数之和最大是多少。
输入格式
第一行有个用空格隔开的整数
和
,表示矩阵有
行
列。
接下来的行是一个
的矩阵,每行的
个整数之间用空格隔开。
输出格式
输出一个整数,表示答案。
数据范围
题解:
设路径长度为,第一条路径末尾位于
,第二条路径末尾位于
,
容易发现有等式成立:,
表示两条路径长度为
,第一条路径末尾在第
行,第二条路径末尾在
行时,已经取得的最大值。
简单附代码:
#include <bits/stdc++.h>
#define Pair pair<int,int>
#define fir first
#define sec second
namespace fastIO{
#define BUF_SIZE 100000
#define OUT_SIZE 100000
//fread->read
bool IOerror=0;
//inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;}
inline char nc(){
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend){
p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1){IOerror=1;return -1;}
}
return *p1++;
}
inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';}
template<class T> inline bool read(T &x){
bool sign=0;char ch=nc();x=0;
for(;blank(ch);ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
inline bool read(double &x){
bool sign=0;char ch=nc();x=0;
for(;blank(ch);ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0';
if(ch=='.'){double tmp=1; ch=nc();for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0');}
if(sign)x=-x;return true;
}
inline bool read(char *s){
char ch=nc();
for(;blank(ch);ch=nc());
if(IOerror)return false;
for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch;
*s=0;
return true;
}
inline bool read(char &c){
for(c=nc();blank(c);c=nc());
if(IOerror){c=-1;return false;}
return true;
}
template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);}
#undef OUT_SIZE
#undef BUF_SIZE
};using namespace fastIO;using namespace std;
const int N=50+5;
const double eps=1e-7;
const double pi=acos(-1.0);
const int mod=998244353;
const int inf=0x3f3f3f3f;
int f[N*2][N][N],c[N][N];
int n,m;
signed main(){
read(n,m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
read(c[i][j]);
f[0][1][1]=c[1][1];
/*1 1 2 x+y=i+2*/
for(int i=0;i<n+m-2;i++)
for(int x1=1;x1<=n&&x1<=i+1;x1++)
for(int x2=1;x2<=n&&x2<=i+1;x2++){
int y1=i+2-x1,y2=i+2-x2;
if(x1==x2){
f[i+1][x1][x2]=max(f[i+1][x1][x2],f[i][x1][x2]+c[x1][y1+1]);//yy
f[i+1][x1+1][x2+1]=max(f[i+1][x1+1][x2+1],f[i][x1][x2]+c[x1+1][y1]);//xx
}
else{
f[i+1][x1][x2]=max(f[i+1][x1][x2],f[i][x1][x2]+c[x1][y1+1]+c[x2][y2+1]);//yy
f[i+1][x1+1][x2+1]=max(f[i+1][x1+1][x2+1],f[i][x1][x2]+c[x1+1][y1]+c[x2+1][y2]);//xx
}
//x y
if(x1+1==x2) f[i+1][x1+1][x2]=max(f[i+1][x1+1][x2],f[i][x1][x2]+c[x1+1][y1]);//xy
else f[i+1][x1+1][x2]=max(f[i+1][x1+1][x2],f[i][x1][x2]+c[x1+1][y1]+c[x2][y2+1]);//xy
if(x2+1==x1) f[i+1][x1][x2+1]=max(f[i+1][x1][x2+1],f[i][x1][x2]+c[x2+1][y2]);//yx
else f[i+1][x1][x2+1]=max(f[i+1][x1][x2+1],f[i][x1][x2]+c[x1][y1+1]+c[x2+1][y2]);//yx
}
printf("%lld\n",f[n+m-2][n][n]);
return 0;
}