G - Minimum Permutation 解説 by inszva

O(N) Using stack

Use a stack to save the answer. Continuing push elements into the stack after popping the back of the stack if it is less that the element and can be pushed later. Skip ones we already pushed into the stack.

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    vector<int> cnt(m+1);
    for (int& x: a) {
        cin >> x;
        cnt[x]++;
    }
    vector<int> vis(m+1);
    vector<int> st;
    for (int x: a) {
        if (!vis[x]) {
            while (!st.empty() && st.back() > x && cnt[st.back()]) {
                vis[st.back()] = 0;
                st.pop_back();
            }
            st.emplace_back(x);
            vis[x] = 1;
        }
        cnt[x]--;
    }
    for (int x: st) cout<< x<<" ";
    cout << endl;
    return 0;
}

投稿日時:
最終更新: