给定一个顺序存储的线性表,请设计一个算法查找该线性表中最长的连续递增子序列。例如,(1,9,2,5,7,3,4,6,8,0)中最长的递增子序列为(3,4,6,8)。
输入格式:
输入第1行给出正整数n(≤105);第2行给出n个整数,其间以空格分隔。
输出格式:
在一行中输出第一次出现的最长连续递增子序列,数字之间用空格分隔,序列结尾不能有多余空格。
输入样例:
15
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
输出样例:
3 4 6 8
#include<bits/stdc++.h>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#
typedef int ELemType;
typedef int Status;
typedef struct
{
ELemType *data;
int length;
int listsize;
}Sqlist;
Status Init_Sq(Sqlist &S)//初始化线性表
{
int n;
cin>>n;
if(!n)return 0;
S.data=(ELemType*)malloc(sizeof(ELemType)*n);
if(!S.data)exit(OVERFLOW);
for(int i=0;i<n;i++)
{
cin>>S.data[i];
}
return OK;
}
void Find_Longest(Sqlist &S)
{
int maxS=0,pos=0,k;//定义一个k记录当前值
for(int i=0;i<S.length;i++)//只需要遍历一次
{
if(!i)k=1;//每次都必须在第一个数初始化k=1
else
{
if(S.data[i]>S.data[i-1])//如果当前元素大于前面的元素k++
k++;
else//如果小于前面的就回归到1
k=1;
if(k>maxS)//当前k如果超过最大值就赋值给maxS
{
maxS=k;
pos=i;//记录当前最大结点位置
}
}
}
if(maxS==1)cout<<S.data[0];//当没有大于2个元素的递增序列时输出第一个元素
else
{
for(int i=(pos-maxS+1);i<=pos;i++)//当前元素向前数的时候要加一
{
if(i!=pos-maxS+1)cout<<" ";
cout<<S.data[i];
}
}
}
int main()
{
Sqlist S;
if(Init_Sq(S))
{
Find_Longest(S);
}
}