标签:
题意: 求二维数组最长不下降子序列
解题:
记忆化搜索, d[i][j]为以 (i, j) 为终点的最长不下降序列的长度,
然后四个方向 dfs ~
#include <bits/stdc++.h> #define ll long long using namespace std; const int maxn = 110; const int INF = 0x3f3f3f3f; char nm[maxn]; int a[maxn][maxn], d[maxn][maxn]; int gx[4] = {1,0,-1,0}, gy[4] = {0,1,0,-1}; int t, r, c; int dfs(int x, int y) { if (d[x][y] != -1) return d[x][y]; d[x][y] = 1; for (int i = 0; i < 4; i ++) { int xx = x + gx[i]; int yy = y + gy[i]; if( xx >= 1 && xx <= r && yy >=1 && yy <= c && a[x][y] > a[xx][yy] ) d[x][y] = max (d[x][y], dfs(xx, yy )+1 ); } return d[x][y]; } int main() { scanf ("%d",&t); getchar(); while (t --){ scanf ("%s%d%d",nm, &r,&c); // 行列 for (int i = 1; i <= r; i ++) { for (int j = 1; j <= c; j ++) { scanf ("%d", &a[i][j]); } } int ans = 0; memset (d, -1, sizeof(d)); // solve for (int i= 1; i <= r; i ++) { for (int j = 1; j <= c; j ++) { ans = max (ans, dfs (i, j) ); } } printf ("%s: %d\n",nm, ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/ember/p/5781895.html