题目大意
给定一个序列 其中包括 N N N 个数,求一个字典序最小的子序列。要求包含 1 1 1 到 k k k 中的每一个数,每一个数有且仅出现一次。
解题思路
用单调栈来做,遍历给定序列的每一个数,如果大于栈顶的数,就压进栈。如果小于就考虑把栈里大于它的数弹出来,这样能使得字典序最小。
但是在弹出栈顶数的时候要判断后面还有没有这个数,如果没有了就不能弹,否则不能满足题目要求。没有的话相当于就卡在了这个位置,它前面的数也都是固定的了。
把所有的数都遍历完之后,栈里的数就是要求的答案。
参考代码
typedef long long LL;
typedef double db;
const int inf = 0x3f3f3f3f;
const LL INF = 1e18;
const int N = 2e5 + 10;
inline int readint() {int x; scanf("%d", &x); return x;}
int a[N], s[N], in[N];
int last[N];
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int m, n; cin >> m >> n;
for(int i = 0; i < m; ++i) {
a[i] = readint();
last[a[i]] = i; //记录最后出现的位置
}
int top = 0;
for(int i = 0; i < m; ++i) {
if (in[a[i]]) continue; //栈里已经有这个数,则跳过
while (top && a[i] < s[top] && last[s[top]] > i) { //如果此时栈里有数且当前数小于栈顶数,且后面还有栈顶的数,则将栈顶数弹出
in[s[top]] = 0;
top--;
}
s[++top] = a[i];
in[a[i]] = 1;
}
for(int i = 1; i <= top; ++i) {
printf("%s%d", i == 1 ? "" : " ", s[i]);
}
return 0;
}