Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael想知道载一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子
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
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子中,一条可滑行的滑坡为24-17-16-1。当然25-24-23-...-3-2-1更长。事实上,这是最长的一条。
输入
输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
输出
输出最长区域的长度。
样例输入
5 5
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
来源
Don't know
样例输出
25
来源
Don't know
思路:还是一个典型的动态规划的问题,就是牵扯到位置,需要用结构体储存。
动态规划有两种模式,一种是“我为人人“由我推导别人,一种是“人人为我”说的是通过别的来推导我。
我为人人:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int r,c;
struct Node {
int a;
int x;
int y;
bool operator < (const Node &s) const {
return a<s.a;
}
} nodes[10100];
int a[110][100],b[110][110];
int main() {
cin>>r>>c;
int cnt=0,ans=1;
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
scanf("%d",&a[i][j]);
nodes[cnt].a=a[i][j];
b[i][j]=1;
nodes[cnt].x=i;
nodes[cnt].y=j;
cnt++;
}
}
sort(nodes,nodes+cnt);
for(int i=0; i<cnt; i++) { //我为人人
int x=nodes[i].x;
int y=nodes[i].y;
if(x+1<=r&&a[x][y]<a[x+1][y]) {
b[x+1][y]=max(b[x+1][y],b[x][y]+1);
ans=max(ans,b[x+1][y]);
}
if(y+1<=c&&a[x][y]<a[x][y+1]) {
b[x][y+1]=max(b[x][y+1],b[x][y]+1);
ans=max(ans,b[x][y+1]);
}
if(x-1>=1&&a[x][y]<a[x-1][y]) {
b[x-1][y]=max(b[x-1][y],b[x][y]+1);
ans=max(ans,b[x-1][y]);
}
if(y-1>=1&&a[x][y]<a[x][y-1]) {
b[x][y-1]=max(b[x][y-1],b[x][y]+1);
ans=max(ans,b[x][y-1]);
}
printf("ans=%d\n",ans);
}
cout<<ans<<endl;
return 0;
}
人人为我:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int R,C;
struct Node{
int i;
int j;
int n;
bool operator <(const Node &s)const{
return n<s.n;
}
}nodes[10010];
int a[101][101];
int b[101][101];
int main(){
scanf("%d %d",&R,&C);
int t=0;
for(int i=1;i<=R;i++){
for(int j=1;j<=C;j++){
scanf("%d",&a[i][j]);
nodes[t].i=i;
nodes[t].j=j;
nodes[t].n=a[i][j];
b[i][j]=1;
t++;
}
}
sort(nodes,nodes+t);
int ans=1;
/* for(int k=0;k<t;k++){//我为人人
int i=nodes[k].i;
int j=nodes[k].j;
if(j-1>=1&&a[i][j]<a[i][j-1]){
b[i][j-1]=max(b[i][j-1],b[i][j]+1);
ans=max(ans,b[i][j-1]);
}
if(i-1>=1&&a[i][j]<a[i-1][j]){
b[i-1][j]=max(b[i-1][j],b[i][j]+1);
ans=max(ans,b[i-1][j]);
}
if(j+1<=C&&a[i][j]<a[i][j+1]){
b[i][j+1]=max(b[i][j+1],b[i][j]+1);
ans=max(ans,b[i][j+1]);
}
if(i+1<=R&&a[i][j]<a[i+1][j]){
b[i+1][j]=max(b[i+1][j],b[i][j]+1);
ans=max(ans,b[i+1][j]);
}
}
*/
for(int k=0;k<t;++k){//人人为我
int i=nodes[k].i;
int j=nodes[k].j;
if(j-1>=1&&a[i][j]>a[i][j-1]){
b[i][j]=max(b[i][j-1]+1,b[i][j]);
ans=max(ans,b[i][j]);
}
if(i-1>=1&&a[i][j]>a[i-1][j]){
b[i][j]=max(b[i-1][j]+1,b[i][j]);
ans=max(ans,b[i][j]);
}
if(j+1<=C&&a[i][j]>a[i][j+1]){
b[i][j]=max(b[i][j+1]+1,b[i][j]);
ans=max(ans,b[i][j]);
}
if(i+1<=R&&a[i][j]>a[i+1][j]){
b[i][j]=max(b[i+1][j]+1,b[i][j]);
ans=max(ans,b[i][j]);
}
}
printf("%d\n",ans);
return 0;
}