栈的模拟
解题思路
题意就是要靠近左边的数字越小越好。每读入一个数 x x x ,先判断此时栈顶的数是否大于 x x x,如果大的话就弹出这个数,直到栈顶的数小于或者等于 x x x。
注意事项
1.本来想直接用栈模拟,输出最后结果的时候要倒着输出,如果用递归的写法会爆栈,故再用一个栈模拟递归输出。
2.也可参考题解,用 deque 模拟,输出更方便~
3.为啥不快读快输会超时orz
参考代码
#include <bits/stdc++.h>
using namespace std;
#define LL long long
//#define LOCAL
const int N = 2e7 + 10;
using namespace std;
inline string read() {
char ch = getchar();
string str1 = "";
while (ch >= '0' && ch <= '9') {
str1 += ch, ch = getchar();
}
return str1;
}
int read_n() {
int x = 0;
char ch = 0;
while (ch < '0' || ch > '9') {
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + (ch - '0');
ch = getchar();
}
return x;
}
stack<int> st, tmp;
//deque<int> q;
bool flag = false;
void print() {
while (!st.empty()) {
tmp.push(st.top()); st.pop();}
while (!tmp.empty()) {
if (!flag) {
if (tmp.top()) {
putchar(tmp.top() + '0');
flag = true;
}
tmp.pop();
} else {
putchar(tmp.top() + '0');
tmp.pop();
}
}
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n, len;
string s;
// getline(cin, s);
s = read();
// scanf("%d", &len);
len = read_n();
for(int i = 0; i < s.size(); i++) {
int now = s[i] - '0';
while (!st.empty() && now < st.top() && len) {
st.pop(); len--;
}
st.push(now);
// while(!q.empty() && q.back() > now && len) {
// q.pop_back(); len--;
// }
// q.push_back(now);
}
//这里注意,len可能还有
// while(len) {
// q.pop_back();
// len--;
// }
while (len) {
st.pop();
len--;
}
print();
// while (!q.empty()) {
// if (!flag) {
// if (q.front()) {
printf("%d", q.front());
// putchar(q.front() + '0');
// flag = true;
// } q.pop_front();
// } else {putchar(q.front() + '0'); q.pop_front();}
// }
if (!flag) putchar('0');
return 0;
}