UVA10285 二维 LIS

题意: 求二维数组最长不下降子序列

解题:

记忆化搜索, 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;
}

 

posted @ 2016-08-17 21:02  Ember  阅读(494)  评论(0编辑  收藏  举报