A Three Indices(单调栈)

题目
题意:给顶一个排列,找三个坐标,满足 a i < a j > a k , i < j < k a_ia_k,iai<aj>ak,i<j<k,存在输出任意一个,不存在输出NO。
思路:先从左到右记录下每个数字是否有比它小的数,再从右到左遍历查找。

#include
using namespace std;
#define ll long long
const int maxn = 3010;

int a[maxn],n;
int mp[maxn];
stack<int> st;

int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%d",&n);
        for(int i = 1;i <= n; ++i) {
            scanf("%d",&a[i]);
        }
        memset(mp, 0 ,sizeof(mp));
        while(!st.empty()) st.pop();
        for(int i = 1;i <= n; ++i) {
            while(!st.empty() && a[st.top()] >= a[i]) {
                st.pop();
            }
            if(!st.empty())
                mp[i] = st.top();
            else
                st.push(i);
        }
//        for(int i = 1;i <= n; ++i) {
//            printf("%d ",mp[i]);
//        }
//        printf("\n");
        while(!st.empty()) st.pop();
        bool flag = 0;
        for(int i = n;i >= 1; --i) {
            while(!st.empty() && a[st.top()] >= a[i]) {
                st.pop();
            }
            if(!st.empty()) {
                if(mp[i]) {
                    flag = 1;
                    printf("YES\n%d %d %d\n",mp[i], i, st.top());
                    break;
                }
            }else
                st.push(i);
        }
        if(!flag) printf("NO\n");
    }
}

你可能感兴趣的:(Codeforces)