Gym - 102423J

J - One of Each(贪心,栈)

大佬的代码,tql。
打比赛的时候没想出来,过后看了看这个代码。
用桶排序的思想,记录每个数字出现的个数,然后用栈实现最小的字典序输出。桶的作用就是判断这个数是不是最后一个数字,如果是最后一个数字就不得不去选了,然后栈的作用就是尽可能将前面的数字变小,如果栈顶的数后面还有,且要插入的数字比这个数小的话,就将栈顶出栈,然后将更小的数入栈。具体代码如下:

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

猜你喜欢

转载自blog.csdn.net/qq_47783181/article/details/112979726
今日推荐