题意:给定一个n*n的矩阵,问从(0,0)开始走,每次最多水平或者垂直走k个格子,且要保证每次到达的格子要大于前一个,问最大和是多少。
析:一个很简单的记忆搜索,dp[i][j],表示到达(i,j)的最大和是多少,我们可以反着推出答案。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #include <list> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 100 + 10; const int mod = 1000007; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } int a[maxn][maxn]; int k; int dp[maxn][maxn]; bool vis[maxn][maxn]; int dfs(int r, int c){ int &ans = dp[r][c]; if(vis[r][c]) return ans; vis[r][c] = true; for(int i = 1; i <= k; ++i) for(int j = 0; j < 4; ++j){ int x = r + dr[j] * i; int y = c + dc[j] * i; if(!is_in(x, y) || a[r][c] >= a[x][y]) continue; ans = max(ans, dfs(x, y)); } return ans += a[r][c]; } int main(){ while(scanf("%d %d", &n, &k) == 2 && k+n != -2){ m = n; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) scanf("%d", &a[i][j]); memset(vis, 0, sizeof vis); memset(dp, 0, sizeof dp); printf("%d ", dfs(0, 0)); } return 0; }