vendredi 2 avril 2021

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;
}

Aucun commentaire:

Enregistrer un commentaire