zoukankan      html  css  js  c++  java
  • 牛客算法周周练15A

    在这里插入图片描述

    题目大意:

    给出 n 个数,下标从 1 开始,依次输出 ai 右边第一个比 ai 大的数的下标,如果没有找到则输出 0 。

    解题思路:

    思路一:枚举
    枚举从 i 到 n 所有的数,找到则输出第一个,没找到则输出 0 ,复杂度是平方阶的,范围1e4 复杂度大概1e8,很容易被卡。AC代码:

    #include <cstdio>
    #include <iostream>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    typedef long long ll;
    const int N = 1e4+50;
    int a[N];
    int main()
    {
        memset(a, 0, sizeof a);
        int n;
        cin >> n;
        for (int i = 1; i <= n; i ++)
            cin >> a[i];
        for (int i = 1; i <= n; i ++)
        {
            bool flag = true;
            for (int j = i+1; j <= n; j ++)
                if(a[j] > a[i])
                {
                    cout << j << " ";
                    flag = false;
                    break;
                }
            if(flag)
              cout << 0 << " ";
        }
        cout << endl;
        //system("pause");
        return 0;
    }
    

    思路二:单调栈模拟
    前面的方法复杂度过大,数据范围再大一点就不行了,这种方法用单调栈模拟,用栈维护一个不上升的序列,只要 a[i] < 栈顶则把 i 进栈,如果遇到比栈顶大的数,则说明这个数是栈里面的数要找的位置,栈内的数全部赋值 i ,然后 i 进栈,重新开始维护序列,让栈里面始终存不上升的序列。AC代码:

    #include <cstring>
    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <stack>
    using namespace std;
    const int N = 1e4+50;
    int a[N], ans[N];
    stack<int > st;
    int main()
    {
        memset(ans, 0, sizeof ans);
        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()])//只要比栈顶大则把栈内元素要找的位置就是 i 
            {
                ans[st.top()] = i;
                st.pop();
            }
            st.push(i);
        }
        for (int i = 1; i <= n; i ++)
          cout << ans[i] << " ";
        cout << endl;
        return 0;
    }
    
  • 相关阅读:
    Spring Boot 2 快速教程:WebFlux 集成 Thymeleaf(五)
    Spring Boot 2 快速教程:WebFlux 集成 Mongodb(四)
    程序兵法:Java String 源码的排序算法(一)
    oracle等待事件以及解决方案
    记一次数据库参数compatible降级[转]
    R中统计假设检验总结(一)
    Kriging插值法
    数学建模小练习(1):插值【转】
    C++11 lambda表达式
    C++11 正则表达式——基础知识介绍
  • 原文地址:https://www.cnblogs.com/Hayasaka/p/14294213.html
Copyright © 2011-2022 走看看