skiing
3000 ms | 内存限制: 65535
5
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。
后面是下一组数据;
输出
输出最长区域的长度。
样例输入
1
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
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
int n,m;
int a[110][110];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct zz
{
int x,y,l;
}f1,f2;
int bfs(int x,int y)
{
queue<zz>q;
int i,j,k;
f1.x=x;f1.y=y;f1.l=1;
q.push(f1);
while(!q.empty())
{
f1=q.front();
q.pop();
for(i=0;i<4;i++)
{
f2.x=f1.x+dx[i];
f2.y=f1.y+dy[i];
if(a[f2.x][f2.y]>0&&a[f2.x][f2.y]<a[f1.x][f1.y])
{
f2.l=f1.l+1;
q.push(f2);
}
}
}
return f1.l;
}
int main()
{
int t;
int i,j;
int max,min;
scanf("%d",&t);
while(t--)
{
max=0;
scanf("%d%d",&n,&m);
memset(a,-1,sizeof(a));
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
min=bfs(i,j);
if(max<min)
max=min;
}
}
printf("%d\n",max);
}
return 0;
}
//又看了一个大神的博客,这种方法更省时(运行时间是上一个的1/10)。。。运用了剪枝。。
<pre class="cpp" name="code">#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int a[110][110],vis[110][110];
int n,m;
int bfs(int x,int y)
{
int b,c,cnt;
if(vis[x][y]>1))//**剪枝,不剪枝应该是TLE的,测试数据有点弱,不过就算没TLE,加了剪枝的时间优化了不少*//
return vis[x][y];];//**如果以前搜索过这点,就直接返回搜索的这点,不用再进行搜索**//
for(int i=0;i<4;i++)
{
b=x+dx[i];
c=y+dy[i];
if(b>=1&&b<=n&&c>=1&&c<=m&&a[x][y]<a[b][c])
{
cnt=bfs(b,c);
if(vis[x][y]<cnt+1)
vis[x][y]=cnt+1;
}
}
return vis[x][y];//**返回这点能取得的最大值**//
}
int main()
{
int t;
int i,j;
scanf("%d",&t);
while(t--)
{
int max=0;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
vis[i][j]=1;
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
bfs(i,j);
if(vis[i][j]>max)
max=vis[i][j];
}
}
printf("%d\n",max);
}
return 0;
}