第一讲 基础算法
AcWing 786. 第k个数
题目描述:AcWing 786. 第k个数。给定一个长度为 n 的整数数列,以及一个整数 k,请用快速选择算法求出数列从小到大排序后的第 k 个数。
输入:
5 3
2 4 1 5 3
输出:
3
#include <bits/stdc++.h>
using namespace std;
const int N=100000+10;
int q[N];
int quick_sort(int q[],int l,int r,int k) {
if(l>=r) return q[l];
int i=l-1,j=r+1,x=q[l+r>>1];
while(i<j) {
do i++;while(q[i]<x);
do j--;while(q[j]>x);
if(i<j) swap(q[i],q[j]);
}
if(j-l+1>=k) return quick_sort(q,l,j,k);
else return quick_sort(q,j+1,r,k-(j-l+1));
}
int main() {
ios::sync_with_stdio(false);cin.tie(0);
int n,k;cin>>n>>k;
for(int i=0;i<n;i++) cin>>q[i];
cout<<quick_sort(q,0,n-1,k)<<endl;
return 0;
}
第二讲 数据结构
AcWing 828. 模拟栈
题目描述:AcWing 828. 模拟栈。实现一个栈,栈初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;
pop
– 从栈顶弹出一个数;
empty
– 判断栈是否为空;
query
– 查询栈顶元素。
现在要对栈进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果。
#include <bits/stdc++.h>
using namespace std;
const int N=100000+10;
int m;
int stk[N],tt;
int main() {
ios::sync_with_stdio(false);cin.tie(0);
cin>>m;
while(m--) {
string op;
int x;
cin>>op;
if(op=="push")
{
cin>>x;
stk[++tt]=x;
}
else if(op=="pop") --tt;
else if(op=="empty") cout<<(tt?"NO":"YES")<<endl;
else cout<<stk[tt]<<endl;
}
return 0;
}
AcWing 3302. 表达式求值
题目描述:给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。
#include <bits/stdc++.h>
using namespace std;
stack<int> num;
stack<char> op;
void eval()
{
auto b=num.top();num.pop();
auto a=num.top();num.pop();
auto c=op.top();op.pop();
int x;
if(c=='+') x=a+b;
else if(c=='-') x=a-b;
else if(c=='*') x=a*b;
else x=a/b;
num.push(x);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
unordered_map<char,int> pr{{'+',1},{'-',1},{'*',2},{'/',2}};
string str;cin>>str;
for(int i=0;i<str.size();i++)
{
auto c=str[i];
if(isdigit(c))
{
int x=0,j=i;
while(j<str.size()&&isdigit(str[j]))
x=x*10+str[j++]-'0';
i=j-1;
num.push(x);
}
else if(c=='(') op.push(c);
else if(c==')')
{
while(op.top()!='(') eval();
op.pop();
}
else
{
while(op.size()&&op.top()!='('&pr[op.top()]>=pr[c]) eval();
op.push(c);
}
}
while(op.size()) eval();
cout<<num.top()<<endl;
return 0;
}