简体   繁体   English

codeforces 超出时间限制

[英]Time limit exceeded on codeforces

I've been stuck on this problem for a pretty Long while.我已经被这个问题困扰了很长时间。 I always get "Time limit exceeded" when I submit the code.提交代码时,我总是收到“超出时间限制”。 My solution is to input the items of the array then determine the largest number in the array and diplay it along with the elements following it and so on.我的解决方案是输入数组的项目,然后确定数组中的最大数字并将其与后面的元素一起显示,依此类推。 How can I make my algorithm more efficient?如何让我的算法更高效?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int T, n;
    cin >> T;
    while (T--) {
        //inputting p[n]
        scanf_s("%d", &n);
        int* p = new int[n];
        for (int i = 0; i < n; i++) {
            scanf_s("%d", &p[i]);
        }

        while (n != 0) {
            //*itr = largest element in the array
            auto itr = find(p, p + n, *max_element(p, p + n));
            int index = distance(p, itr);

            for (int i = index; i < n; i++) {
                printf("%d\n", p[i]);
            }
            //deleting element by decreasing n:
            n = index;
        }

        delete[] p;
    }
    return 0;
}

You solution is O(n^2), too slow.你的解决方案是 O(n^2),太慢了。

AO(n) solution is obtained by iteratively calculating the position of the max element until a given index i . AO(n) 解是通过迭代计算最大元素的 position 直到给定索引i获得的。

#include <iostream>
#include <vector>
#include <algorithm>
//using namespace std;

int main() {
    int T;
    std::cin >> T;
    while (T--) {
        //inputting p[n]
        int n;
        std::cin >> n;
        std::vector<int> p(n);
        for (int i = 0; i < n; i++) {
            std::cin >> p[i];
        }
        std::vector<int> max_before(n);
        max_before[0] = 0;
        for (int i = 1; i < n; ++i) {
            if (p[i] > p[max_before[i-1]]) {
                max_before[i] = i;
            } else {
                max_before[i] = max_before[i-1];
            }
        }

        while (n != 0) {
            int index = max_before[n-1];
            for (int i = index; i < n; i++) {
                std::cout << p[i] << " ";
            }
            //deleting element by decreasing n:
            n = index;
        }
        std::cout << '\n';
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM