题目链接:http://poj.org/problem?id=1088
Dynamic programming
将2D input array按照递减迅速排列组成original sequence,最终答案一定是这个的sub-sequence.在original sequence中找到符合条件(相邻的两个的位置必须是相邻的)的最长递减序列。代码如下:
1 #include <iostream> 2 #include <math.h> 3 #include <stdio.h> 4 #include <cstdio> 5 #include <algorithm> 6 #include <string.h> 7 #include <string> 8 #include <sstream> 9 #include <cstring> 10 #include <queue> 11 #include <vector> 12 #include <functional> 13 #include <cmath> 14 #include <set> 15 #define SCF(a) scanf("%d", &a) 16 #define IN(a) cin>>a 17 #define FOR(i, a, b) for(int i=a;i<b;i++) 18 #define Infinity 9999999 19 typedef long long Int; 20 using namespace std; 21 22 struct height 23 { 24 int x, y; 25 int h; 26 }; 27 28 bool cmp(height h1, height h2) 29 { 30 return h1.h > h2.h; 31 } 32 33 int main() 34 { 35 height hs[10005]; 36 int R, C; 37 int f[10005]; 38 while (scanf("%d %d", &R, &C) != EOF) 39 { 40 int index = 0; 41 FOR(i, 0, R) 42 { 43 FOR(j, 0, C) 44 { 45 int h; 46 SCF(h); 47 hs[index].x = i; 48 hs[index].y = j; 49 hs[index++].h = h; 50 } 51 } 52 53 sort(hs, hs + index, cmp); 54 FOR(i, 0, index) 55 f[i] = 1; 56 f[0] = 1; 57 int mh = 1; 58 FOR(i, 1, index) 59 { 60 for (int j = i - 1; j >= 0; j--) 61 { 62 if (hs[i].h < hs[j].h && (abs(hs[i].x - hs[j].x) + abs(hs[i].y - hs[j].y)) == 1) 63 { 64 f[i] = max(f[i], f[j] + 1); 65 mh = max(f[i], mh); 66 } 67 } 68 } 69 printf("%d\n", mh); 70 } 71 return 0; 72 }