牛客刷题-Day25
牛客刷题-Day25
今日刷题:\(A-E\)
A 栈和排序

解题思路
题目要求尽可能按照字典序最大的顺序进行出栈操作,则设置变量 \(tmp\) 表示当前期望出栈的元素:
- 当入栈元素等于 \(tmp\) 时,直接出栈;
- 当入栈元素不等于 \(tmp\) 时,仅入栈;
最终若栈中还有元素,依次出栈即可得到最终的出栈序列。这里的出栈判断实际是贪心策略,每次尽可能让当前最大的元素(即等于 \(tmp\))出栈。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n;
int stk[N], tt;
int main() {
scanf("%d", &n);
int tmp = n;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
if (x == tmp) {
tmp--;
printf("%d ", x);
} else {
stk[++tt] = x;
}
}
while (tt)
printf("%d ", stk[tt--]);
return 0;
}
B 牛牛与后缀表达式

解题思路
这里每次匹配到运算符,则将栈顶的两个元素出栈,进行运算,将结果入栈,最终栈顶元素为最终结果。
注意:下面的代码未处理元素为负数的情况,但可以通过牛客的测评,实际还是需要考虑全面。
C++ 代码
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(string str) {
long long tmp = 0;
for (int i = 0; str[i]; i++) {
if (str[i] >= '0' && str[i] <= '9') {
tmp = tmp * 10 + str[i] - '0';
} else if (str[i] == '#') {
stk.push(tmp);
tmp = 0;
} else {
long long b = stk.top();
stk.pop();
long long a = stk.top();
stk.pop();
if (str[i] == '+') {
stk.push(a + b);
} else if (str[i] == '-') {
stk.push(a - b);
} else {
stk.push(a * b);
}
// printf("%lld\n", stk.top());
}
}
return stk.top();
}
private:
stack<long long> stk;
};
C 好串

解题思路
根据题意,每次操作,都是插入字符串 ab,则 a 和 b 每次插入都是成对存在的且 a 在前方,因此通过栈进行匹配,最终栈为空,则说明所有的 a 和 b 都匹配成功,该字符串为 Good;否则,为 Bad。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
string s;
stack<char> stk;
int main() {
cin >> s;
for (int i = 0; s[i]; i++) {
if (s[i] == 'b' && (!stk.empty() && stk.top() == 'a')) {
stk.pop();
} else {
stk.push(s[i]);
}
}
if (!stk.empty())
puts("Bad");
else
puts("Good");
return 0;
}
D Rails

解题思路
按照 \(1~n\) 的顺序入栈,给出一个出栈序列,判断出栈序列是否合法。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, a[N];
int stk[N], tt;
bool end() {
cin >> n;
if (n) return false;
return true;
}
int main() {
while (!end()) {
cin >> a[0];
while (a[0]) {
tt = 0;
a[1] = a[0];
for (int i = 2; i <= n; i++)
cin >> a[i];
for (int i = 1, j = 1; i <= n; i++) {
stk[++tt] = i;
while (tt && stk[tt] == a[j]) {
tt--;
j++;
}
}
if (tt)
puts("No");
else
puts("Yes");
cin >> a[0];
if (!a[0])
cout << endl;
}
}
return 0;
}
E 吐泡泡

解题思路
分情况讨论:
- 栈顶为
o且入栈元素为o,则栈顶元素出栈与入栈元素合成O,此时,若栈顶还有元素且为O,则栈顶元素出栈,否则合成的O入栈; - 栈顶为
O且入栈元素为O,则栈顶元素出栈; - 其余情况,元素入栈。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int T;
int stk[N], tt;
string s;
int main() {
cin >> T;
while (T--) {
tt = 0;
cin >> s;
for (int i = 0; s[i]; i++) {
if (s[i] == 'o' && (tt && stk[tt] == ('o' - 'a'))) {
tt--;
if (tt && stk[tt] == ('O' - 'a'))
tt--;
else
stk[++tt] = 'O' - 'a';
} else if (s[i] == 'O' && (tt && stk[tt] == ('O' - 'a'))) {
tt--;
} else {
stk[++tt] = s[i] - 'a';
}
}
for (int i = 1; i <= tt; i++)
cout << (char) (stk[i] + 'a');
cout << endl;
}
return 0;
}
本文来自博客园,作者:Cocoicobird,转载请注明原文链接:https://www.cnblogs.com/Cocoicobird/p/19293046
浙公网安备 33010602011771号