- 下面是第一遍的代码,结果超时了,考虑改进一下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;
int k=0;
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];
}
}
return 0;
}
#include <iostream>
#include <stack>
using namespace std;
int num[101000];
int num_post_max[101000];
int order[101000];
int j=0;
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;
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();
sta.pop();
}
int temp=0;
for(int i=0;i<j;i++)
{
if(++temp==1)
{
cout << order[i];
}
else
{
cout << ' ' << order[i];
}
}
return 0;
}