AB5 点击消除
关键思路:如何消除 + 栈
// 结合AB 3的有效括号序列,消除的思想
#include <bits/stdc++.h>
using namespace std;
// 辅助栈
stack<char> stk;
string str;
int main() {
cin >> str;
int lenStr = str.size();
stk.push(str[0]); // 先把第一个字符压入栈中
for (int i = 1; i < lenStr; ++i) {
// 栈空,就要先压入栈,若栈不空则判断。。。
if (stk.empty()) stk.push(str[i]);
else if (str[i] != stk.top()) {
// 若当前指针指向的元素不等于栈顶元素,说明不匹配,就先压入栈,若匹配就消掉
stk.push(str[i]);
}else {
stk.pop();
}
}
// 最终,若栈为空,就输出0,否则要从栈底打印到栈顶,就要多加一步操作了
if (stk.empty()) cout << '0' << endl;
else {
vector<char> res; // 最终存储的结果
while (!stk.empty()) {
// 若栈不空
res.push_back(stk.top());
stk.pop();
}
int lenRes = res.size();
for (int i = lenRes - 1; i >= 0; --i) {
cout << res[i];
}
cout << endl;
}
return 0;
}
AB7 【模板】队列
hh : 队头(初始化0),tt : 队尾(初始化 -1); 一旦hh > tt 即代表队列为空
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int que[N];
int hh; //队头0
int tt = -1; //队尾-1
// 当 hh > tt时,即队列为空
string op; //操作的名称
// 队列是先进先出的,从队尾进入,从队头出去
void pushOP(int x) {
que[++tt] = x;
}
// 因为会在操作的时候判断是否为空,所以函数这里就减少操作
void popOP() {
hh++;
}
// 队列是从队头出来的
int getFront() {
return que[hh];
}
bool isEmpty() {
// true 空
if (hh > tt) return true;
else return false;
}
int m; //操作的次数
int main () {
cin >> m;
int x;// 要插入队尾的数
while (m--) {
cin >> op;
if (op == "push") {
cin >> x;
pushOP(x);
}else if (op == "pop") {
if (isEmpty()) cout << "error" << endl;
else {
int k = getFront();
popOP();
cout << k << endl;
}
}else {
if (isEmpty()) cout << "error" << endl;
else {
cout << getFront() << endl;
}
}
}
return 0;
}
CD1 在行列都排好序的矩阵中找指定的数
关键思路:简单模拟,即时比较
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, m, k;
int mrx[N][N];
bool flag = false;
int main () {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf ("%d", &mrx[i][j]);
if (k == mrx[i][j]) {
flag = true;
break; // 及时跳出循环
}
}
}
if (flag) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
但是根据这个题目所说的,这个矩阵的每一行每一列是排好序的,那么我们就可以做一个优化,来减少时间;(根据行列升序的性质来进行优化)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, m, k;
int mrx[N][N];
int main () {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf ("%d", &mrx[i][j]);
}
}
// 从右上角开始,仔细想想,其实不会漏掉元素判断
int i = 0;
int j = m - 1;
while (i < n &&j >= 0) {
if (mrx[i][j] == k) {
printf ("Yes\n");
return 0;
}
else if (mrx[i][j] > k) {
j--;
}else{
i++;
}
}
printf ("No\n");
return 0;
}
但我决定即时判断也可以算快的,能找到就可以及时退出了