算法作业station

在这里插入图片描述

  • 下面是第一遍的代码,结果超时了,考虑改进一下post数组的求法,可以直接在最开始就从后向前遍历一遍数组,记录当前比较得到的最大值并记录下来。
#include <iostream>
#include <stack>
#define maxSize 100010
using namespace std;
int num[maxSize];
int order[maxSize];
int *post;//后续数组 
int main()
{
	int n;
	int pmax=0;
	int j=0;//搜索标志 
	int a;//临时存储pop出来的变量
	int k=0;//order数组尾标记 
	cin >> n;
	stack <int> s;
	for(int i=0;i<n;++i)
	{
		cin >> num[i];
	}
	post=&(num[j]);
	pmax=num[j];
	for(int i=0;post[i]!='\0';++i)
	{
		if(post[i]>pmax)
		{
			pmax=post[i];
		}
	}
	while(true)
	{
		if(num[j]=='\0'&&s.empty()==1)
		{
			break;
		}
		while(s.empty()==1 || pmax>s.top())
		{
			s.push(num[j++]);
			post=&(num[j]);
			pmax=num[j];
			for(int i=0;post[i]!='\0';++i)
			{
				if(post[i]>pmax)
				{
					pmax=post[i];
				}
			}
		}
		a=s.top();
		s.pop();
		order[k++]=a;
	}
	int temp=0;
	for(int i=0;i<k;i++)
	{
		if(++temp==1)
		{
			cout << order[i];
		}
		else
		{
			cout << ' ' << order[i];
		}
	}
//	cout << endl;
	return 0;
} 
  • 看不懂之前写的就重新写了一遍,测试通过
#include <iostream>
#include <stack>
using namespace std;
int num[101000];
int num_post_max[101000];
int order[101000];
int j=0;//遍历游标,用于order数组
int main(){
	int n;
	cin >> n;
	for(int i=0;i<n;++i){
		cin >> num[i];
	}
	int pmax_sub = n-1;
	for(int i=n-1;i>=0;--i){
		if(num[i]>num[pmax_sub]){
			pmax_sub=i;
		}
		num_post_max[i]=num[pmax_sub];
	}
	int k=0;//遍历游标,用于num数组
	int top=0;
	stack <int> sta;
	sta.push(num[k++]);
	while(true)
	{
		if(num[k]=='\0'&&sta.empty()==1)
		{
			break;
		}
		while(sta.empty()==1 || num_post_max[k]>sta.top())
		{
			sta.push(num[k++]);
		}
		order[j++]=sta.top();//输出序列用order存储
		sta.pop();
	}
	
	//最后没有多余空格的输出
	int temp=0;
	for(int i=0;i<j;i++)
	{
		if(++temp==1)
		{
			cout << order[i];
		}
		else
		{
			cout << ' ' << order[i];
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值