题面说的有点问题,应该是向后看齐。
于是我们维护一个单调递减栈,如果当前a[i]比栈顶元素大,就执行pop操作,然后把pop出来的元素的答案都用 i 更新即可。
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 using namespace std;12 #define enter puts("") 13 #define space putchar(' ')14 #define Mem(a) memset(a, 0, sizeof(a))15 typedef long long ll;16 typedef double db;17 const int INF = 0x3f3f3f3f;18 const db eps = 1e-8;19 const int maxn = 1e5 + 5;20 inline ll read()21 {22 ll ans = 0;23 char ch = getchar(), last = ' ';24 while(!isdigit(ch)) {last = ch; ch = getchar();}25 while(isdigit(ch)) {ans = ans * 10 + ch - '0'; ch = getchar();}26 if(last == '-') ans = -ans;27 return ans;28 }29 inline void write(ll x)30 {31 if(x < 0) x = -x, putchar('-');32 if(x >= 10) write(x / 10);33 putchar(x % 10 + '0');34 }35 36 int n, a[maxn];37 #define pr pair 38 #define mp make_pair39 stack st;40 int ans[maxn];41 42 int main()43 {44 n = read();45 for(int i = 1; i <= n; ++i) a[i] = read();46 for(int i = 1; i <= n; ++i)47 {48 while(!st.empty() && st.top().first < a[i])49 {50 pr node = st.top(); st.pop();51 ans[node.second] = i;52 }53 st.push(mp(a[i], i));54 }55 for(int i = 1; i <= n; ++i) write(ans[i]), enter;56 return 0;57 }