给定一个矩阵,要求找出数值递减的最长序列,比如矩阵:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9 最长的数值递减序列是25,24,23,22........1, 长度 25
问题满足后无效性,以某个数字结尾的最长序列只和以四周数字结尾的最长序列有关,和数组最长子序列类似,只不过最长子序列可以不连续,那么最长子序列的之前的子问题应该就是所有已经有解的数字。
// 1002.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <memory.h>
#include <queue>
using namespace std;
static const int MAX_ROW=100;
static const int MAX_COL=100;
int actualRow = MAX_ROW;
int actualCol = MAX_COL;
int gMatrix[MAX_ROW][MAX_COL] = {0};
int gPathLen[MAX_ROW*MAX_COL] = {0};
typedef struct _node
{
int row;
int col;
int value;
_node(int i,int j, int v)
{
row = i;
col = j;
value = v;
};
_node()
{};
}Node;
struct _greater
{
bool operator()(const Node& _Left, const Node& _Right) const
{
return (_Left.value > _Right.value);
}
};
int getMaxAdjLen(const Node& current)
{
int result = 0;
if (current.row > 0)
{
result = gPathLen[(current.row-1)*actualCol + current.col] > result ?
gPathLen[(current.row-1)*actualCol + current.col] : result;
}
if (current.row < actualRow)
{
result = gPathLen[(current.row+1)*actualCol + current.col] > result ?
gPathLen[(current.row+1)*actualCol + current.col] : result;
}
if (current.col > 0)
{
result = gPathLen[current.row*actualCol + current.col -1 ] > result ?
gPathLen[current.row*actualCol + current.col -1] : result;
}
if (current.col < actualCol)
{
result = gPathLen[current.row*actualCol + current.col +1 ] > result ?
gPathLen[current.row*actualCol + current.col +1] : result;
}
return result;
};
int main()
{
int ar;
int ac;
int maxLen ;
Node tmp;
priority_queue<Node,vector<Node>,_greater> Queue;
while(scanf("%d%d",&ar,&ac) == 2)
{
actualCol = ac;
actualRow = ar;
maxLen = 0;
memset(gPathLen,0,sizeof(int)*MAX_ROW*MAX_COL);
memset(gMatrix,0,sizeof(int)*MAX_ROW*MAX_COL);
for(int i=0;i<ar;i++)
for(int j=0;j<ac;j++)
{
scanf("%d",&gMatrix[i][j]);
Queue.push(Node(i,j,gMatrix[i][j]));
}
while(!Queue.empty())
{
tmp = Queue.top();
Queue.pop();
gPathLen[tmp.row*ac+tmp.col] = getMaxAdjLen(tmp) + 1;
maxLen = gPathLen[tmp.row*ac+tmp.col] > maxLen ? gPathLen[tmp.row*ac+tmp.col] : maxLen;
}
printf("%d",maxLen);
while(!Queue.empty())
Queue.pop();
}
return 0;
};