for循环就好,用一个变量来保存当前符合条件的下标
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4+5;
typedef long long LL;
stack<int>s;//栈存放的是下标
int a[N],b[N];
int main(){
int n;cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=n;i>=1;i--){
while(s.size()&&a[s.top()]<=a[i])s.pop();
if(s.size())b[i]=s.top();
else b[i]=0;
s.push(i);
}
for(int i=1;i<=n;i++){
if(i!=1)cout<<" ";
cout<<b[i];
}
system("pause");
return 0;
}
关于题意理解:
以样例为例:
从当前下标开始:
第一个比3大的数是6,B为3
第一个比2大的数是6,B为3
没有比6大的数, B为0
第一个比1大的数为2,B为6
第一个比1大的数为2,B为6
没有比2大的数 B为0
因此B数列为{3 3 0 6 6 0}
下述方式供题主参考:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n,j,i;
int a[10010],b[10010];
cin>>n;
for (i=1;i<=n;i++)
cin>>a[i];
for (i=1;i<=n;i++)
{
for (j=i+1;j<=n;j++)
{
if (a[j]>a[i])
{
b[i] = j;
break;
}
if (j>n)
b[i] = 0;
}
}
for (i=1;i<n;i++)
cout<<b[i]<<" ";
cout<<b[n]<<endl;
return 0;
}
运行结果: