题解:AT_abc474_c Remove and Append

· · 题解

其实这道题只需要使用双向链表来进行一个模拟即可,但这里有一个问题,就是双向链表查询时间高达线性时间复杂度,所以需要使用哈希表存储每个节点的位置。

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n, q;
    cin >> n >> q;
    list<int> lru;
    unordered_map<int, list<int>::iterator> pos;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        lru.push_back(x);
        pos[x] = prev(lru.end());
    }
    while (q--) {
        int x;
        cin >> x;
        lru.erase(pos[x]);
        lru.push_back(x);
        pos[x] = prev(lru.end());
    }
    for (int x : lru) {
        cout << x << " ";
    }
    return 0;
}