Basic course of algorithm

本文介绍了两部分内容:1. 使用快速选择算法求解AcWing786问题,找出整数数列中第k小的数;2. 实现模拟栈,完成基本操作如push、pop、empty和query。通过实例演示了算法与数据结构在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一讲 基础算法

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JIeJaitt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值