poj1088

题意:有一个矩阵,要求在矩阵上找到一个四方向行走的路线,使得每走一步走到的格子中的数字都比上一步的要小,问路线最长有多长。

分析:先将所有格子按数字大小排序。然后从最大的开始,每次看其四周是否有能走的格子,并更新四周格子的路线长度(每个格子中有一个变量记录以该格子为终点的最长路线长度)。

当然,除了上述方法,还可以用记忆化搜索

#include <iostream>

#include <algorithm>

using namespace std;



const    int        maxr = 102;



struct cpoint

{

    int        x, y, height;

}f[maxr * maxr];



int        r, c, total, map[maxr][maxr], pos[maxr][maxr], dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};



bool operator< (cpoint a, cpoint b)

{

    return a.height > b.height;

}



void init()

{

    int        i, j;



    scanf("%d%d", &r, &c);

    total = 0;

    for (i = 1; i <= r; i++)

        for (j = 1; j <= c; j++)

        {

            scanf("%d", &f[total].height);

            map[i][j] = f[total].height;

            pos[i][j] = 1;

            f[total].x = i;

            f[total].y = j;

            total++;

        }

}



void work()

{

    int        i, j, ans = 1;



    for (i = 0; i < total; i++)

        for (j = 0; j < 4; j++)

            if (map[f[i].x][f[i].y] < map[f[i].x + dir[j][0]][f[i].y + dir[j][1]] && pos[f[i].x][f[i].y] < pos[f[i].x + dir[j][0]][f[i].y + dir[j][1]] + 1)

            {

                pos[f[i].x][f[i].y] = pos[f[i].x + dir[j][0]][f[i].y + dir[j][1]] + 1;

                if (pos[f[i].x][f[i].y] > ans)

                    ans = pos[f[i].x][f[i].y];

            }

    printf("%d\n", ans);

}



int main()

{

    //freopen("t.txt", "r", stdin);

    init();

    sort(f, f + r * c);

    work();

    return 0;

}
View Code

 

你可能感兴趣的:(poj)