阶梯问题

来源:百度知道 编辑:UC知道 时间:2024/06/10 15:22:53
我们用一个正整数列来表示一段地方的高度,当一段地方的高度为一个逐一上升的序列时,我们称它为一个阶梯,例如4、5、6、7、8、是一个长度为5的阶梯。现在给定一个正整数列,请找出它第一个最长的阶梯,并将其输出。如果一个阶梯也没有。输出“NO ans”
运行结果示例 :
请输入数列长度:8
请输入数列:0 2 3 4 3 4 5 8
结果为 2 3 4
本程序必须用C++编程。

#include<iostream>
using namespace std;
const int Max=1000;//数列个数上限
int Arrey[Max];//数组记录原始数列
int Sub[Max];//记录阶梯子列

int IsGood(const int &i,const int& lenth)//找到阶梯并返回阶梯长度
{
int count=1;
for(int j=i+1;j<lenth;j++)
{
if(Arrey[j]-Arrey[i]==j-i)
count++;
else
return count;
}
return count;
}

int main()
{
int lenth;
int subl,oldl=1;
cout<<"请输入数列长度:"<<endl;
cin>>lenth;
cout<<"请输入数列:"<<endl;
for(int i=0;i<lenth;i++)
cin>>Arrey[i];
for(i=0;i<lenth;i++)//循环找到每个阶梯子列
{
subl=IsGood(i,lenth);//得到子列长度
if(subl>oldl)//用较大的阶梯子列替换原有的
{
oldl=subl;
for(int j=0;j<oldl;j++)
Sub[j]=Arrey[j+i];
}
}
if(oldl==1)//子列长度为1说明没有阶梯子列
cout<<"No ans";
else
for(int j=0;j<o