传送门:CodeForces-1353F
思路分析
对于每一条路径,一定有一个点作为基准,这个点的值不会改变,通过改变其他的值来使这条路径满足,这个可以通过反证法得到。
那么枚举每一个点作为基准时的最下花费进行DP,可以先把每个点的值减去到起点的曼哈顿距离方便计算
样例输入
5
3 4
1 2 3 4
5 6 7 8
9 10 11 12
5 5
2 5 4 8 3
9 10 11 5 1
12 8 4 2 5
2 2 5 4 1
6 8 2 4 2
2 2
100 10
10 1
1 2
123456789876543 987654321234567
1 1
42
样例输出
9
49
111
864197531358023
0
AC代码
#include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
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;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
int n,m;
ll a[111][111],dp[111][111];
ll gao(ll x){
for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) dp[i][j]=1e18;
dp[1][1]=a[1][1]-x;
if(dp[1][1]<0) return 1e18;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(i==1&&j==1) continue;
if(a[i][j]>=x) dp[i][j]=min(dp[i-1][j],dp[i][j-1])+a[i][j]-x;
}
}
return dp[n][m];
}
int main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int t;
read(t);
while(t--){
read(n,m);
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) read(a[i][j]),a[i][j]-=i+j;
ll ans=1e18;
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) ans=min(ans,gao(a[i][j]));
printf("%lld\n",ans);
}
return 0;
}