CF637B Chat Order 题解
Content
有 \(n\) 个字符串,每次出现这个单词就把这个单词放到队列的队首(若已经出现就把原队列里面的那个单词提到队首),求最后的队列由队首到队尾的元素依次是多少。
数据范围:\(1\leqslant n\leqslant 2\times 10^5\)。
Solution
直接用结构体存储一下每个字符串最后出现的位置(可以用 \(\texttt{map}\) 直接映射),然后我们按出现的位置从大到小排序即可。
Code
#include <cstdio>
#include <algorithm>
#include <map>
#include <iostream>
using namespace std;
struct node {
string name;
int last;
bool operator < (const node& cjy) const {return last > cjy.last;}
}a[200007];
map<string, int> vis;
int n, cnt;
int main() {
//This program is written in Ubuntu 16.04 by Eason_AC
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
string s;
cin >> s;
if(!vis[s]) {
a[++cnt].name = s;
vis[s] = cnt;
}
a[vis[s]].last = i;
}
sort(a + 1, a + cnt + 1);
for(int i = 1; i <= cnt; ++i)
cout << a[i].name << endl;
return 0;
}