Gym - 102423J

J-One of Each (greedy, stack)

Big guy's code, tql.
I didn't think of it when I was playing the game, so I looked at this code later.
Using the idea of ​​bucket sorting, record the number of occurrences of each number, and then use the stack to achieve the smallest lexicographical output. The function of the bucket is to judge whether the number is the last number. If it is the last number, you have to choose it. Then the function of the stack is to make the previous number as small as possible. If the inserted number is smaller than this number, the top of the stack is popped, and then the smaller number is pushed onto the stack. The specific code is as follows:

#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 2e3 + 10;
const double PI = acos(-1.0);
typedef pair<int, int> PII;
int a[maxn], tong[maxn];
bool vis[maxn];
vector<int> ans;
int main(int argc, char const *argv[]) {
    
    
    int n, k;
    cin >> n >> k;
    for (int i = 0; i < n; i++) {
    
    
        scanf("%d", &a[i]);
        tong[a[i]]++;
    }
    stack<int> sta;
    for (int i = 0; i < n; i++) {
    
    
        if (vis[a[i]]) {
    
    
            tong[a[i]]--;
            continue;
        }
        while (sta.size() && a[i] < sta.top() && tong[sta.top()] != 0) {
    
    
            vis[sta.top()] = 0;
            sta.pop();
        }
        sta.push(a[i]);
        vis[a[i]] = 1;
        tong[a[i]]--;
    }
    while (sta.size()) {
    
    
        ans.push_back(sta.top());
        sta.pop();
    }
    for (int i = ans.size() - 1; i >= 0; i--) {
    
    
        printf("%d%c", ans[i], i == 0 ? '\n' : ' ');
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_47783181/article/details/112979726