3 solutions

  • 5
    @ 2024-7-18 19:26:48

    单调栈用于维护一个区间,栈内的元素是有序的(“序”可以自定义,不一定是从小到大)

    代码

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 3000005;
    int a[N];
    int s[N],top;
    int ans[N],h[N];
    bool cmp(int b,int c){
    	return b > c;
    }
    int main(int argc, char **argv){
    	int n;
    	cin >> n;
    	for (int i = 1;i <= n;i++){
    		cin >> a[i];
    	}
    	for (int i = n;i > 0;i--){	// 从后往前找,因为是找第 i 个元素后面的数
    		// 从大到小排,记得重写规则
    		top = lower_bound(s,s + top,a[i],cmp) - s;
    		// s[top] 是不合法的,s[top-1] 才是合法的
    		ans[i] = h[top - 1];
    		s[top] = a[i];
    		h[top++] = i;
    	}
    	for (int i = 1;i <= n;i++){
    		printf("%d ",ans[i]);
    	}
    	return 0;
    }
    
    • 0
      @ 2026-5-6 18:51:15
      #include <bits/stdc++.h>
      using namespace std;
      using ll = long long;
      
      const int N = 3e6 + 10;
      int a[N], pos[N];
      stack<int> st;
      
      int main() {
      	ios::sync_with_stdio(false);
      	cin.tie(0);
      	cout.tie(0);
      	int n;
      	cin >> n;
      	for (int i = 1; i <= n; i++) {
      		cin >> a[i];
      	}
      	for (int i = 1; i <= n; i++) {
      		while (!st.empty() && a[i] > a[st.top()]) {
      			pos[st.top()] = i;
      			st.pop();
      		}
      		st.push(i);
      	}
      	for (int i = 1; i <= n; i++) {
      		cout << pos[i] << ' ';
      	}
      	cout << '\n';
      	return 0;
      }
      
      • -5
        @ 2024-7-18 18:49:25

        避免抄袭,注释代码自行打

        #include<iostream>
        #include<stack>
        using namespace std;
        int n;
        int a[3114514];
        int p[3114514];
        stack<int>s;
        int main()
        {
            cin>>n;
            //输入
            for(/* i 进行倒推*/)
            {
                while(/*判断条件*/)
                {
                    s.pop();
                }
                if(s.size())
                {
                    p[i]=/*自行推*/
                }
                else
                {
                    p[i]=0;
                }
                s.push(i);
            }
            //输出
            return 0;
        }
        
      • 1

      Information

      ID
      4622
      Time
      1000ms
      Memory
      125MiB
      Difficulty
      3
      Tags
      # Submissions
      68
      Accepted
      18
      Uploaded By