[洛谷] 刷题栈 队列

news2024/10/5 21:19:02

目录

1.后缀表达式

2.表达式括号匹配 

3.表达式求值 

4.表达式的转换

5.机器翻译 


1.后缀表达式

后缀表达式 - 洛谷

#include<iostream>
#include<cstdio>
using namespace std;

int stk[100]; // 用于存储操作数的栈
int index = 0; // 栈顶索引

int main() {
	char op; // 当前读取的字符
	int now = 0; // 当前构建的数字
	bool readingNumber = false; // 是否正在读取一个数字

	while ((op = getchar()) != '@') { // 读取字符直到结束符 '@'
		if (op >= '0' && op <= '9') {
			// 构建当前数字
			now *= 10;
			now += op - '0';
			readingNumber = true;
		}
		else if (op == '.') {
			// 数字结束,压入栈中
			if (readingNumber) {
				stk[++index] = now;
				now = 0;
				readingNumber = false;
			}
		}
		else if (op == '+') {
			// 加法操作
			stk[index - 1] = stk[index - 1] + stk[index];
			index--;
		}
		else if (op == '-') {
			// 减法操作
			stk[index - 1] = stk[index - 1] - stk[index];
			index--;
		}
		else if (op == '*') {
			// 乘法操作
			stk[index - 1] = stk[index - 1] * stk[index];
			index--;
		}
		else if (op == '/') {
			// 除法操作,结果向零取整
			stk[index - 1] = stk[index - 1] / stk[index];
			index--;
		}
	}

	// 输出最终结果
	cout << stk[1] << endl;

	return 0;
}

2.表达式括号匹配 

表达式括号匹配 - 洛谷

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main()
{
	string s;
	cin >> s;
	int isMatch = 0;
	for (int i = 0; i < s.length(); i++) {
		if (s[i] == '(') {
			isMatch++;
		}
		else if (s[i] == ')') {
			isMatch--;
			if (isMatch < 0) {
				cout << "NO";
				return 0;
			}
		}
	}
	if (!isMatch) {
		cout << "YES";
	}
	else {
		cout << "NO";
	}

	return 0;

}

3.表达式求值 

[NOIP2013 普及组] 表达式求值 - 洛谷

如果用Python

print(intput()%10000)

首先是思路:

  • 可以用一个栈储存运算符

  • 并用另一个栈储存需要运算的数字

#include <iostream>
#include <stack>
#include <string>

using namespace std;

stack<int> num; // 定义一个栈存储数字
stack<char> op; // 定义一个栈存储运算符
string input;
int sum = 0, ans, t, t1, t2; // t, t1, t2均为临时变量

int applyOp(int a, int b, char oper) {
    if (oper == '*') return (a * b) % 10000;
    if (oper == '+') return (a + b) % 10000;
    return 0;
}

int main() {
    cin >> input;
    for (int i = 0; i < input.length(); i++) {
        if (isdigit(input[i])) { // 字符转数字
            sum = sum * 10 + (input[i] - '0');
            if (i == input.length() - 1 || !isdigit(input[i + 1])) {
                sum = sum % 10000; // 取模,后四位
                num.push(sum);
                sum = 0;
            }
        }
        else if (input[i] == '+' || input[i] == '*') { // 运算符
            while (!op.empty() && (op.top() == '*' || (op.top() == '+' && input[i] == '+'))) {
                t1 = num.top(); num.pop();
                t2 = num.top(); num.pop();
                t = applyOp(t2, t1, op.top());
                op.pop();
                num.push(t);
            }
            op.push(input[i]);
        }
    }

    while (!op.empty()) {
        t1 = num.top(); num.pop();
        t2 = num.top(); num.pop();
        t = applyOp(t2, t1, op.top());
        op.pop();
        num.push(t);
    }

    ans = num.top(); // 可直接输出栈顶元素
    cout << ans << endl;
    return 0;
}

4.表达式的转换

表达式的转换 - 洛谷

#include <bits/stdc++.h>
using namespace std;
stack<char> dat, op;
stack<int> num, dat2;
int check(char c)
{
	switch (c)
	{
	case '+':return 1;
	case '-':return 1;
	case '*':return 2;
	case '/':return 2;
	case '^':return 3;
	case '(':return 0;
	case ')':return 0;
	default:return -1;
	}
}
int js(int x, int y, char t)
{
	switch (t)
	{
	case '+':return x + y;
	case '-':return x - y;
	case '*':return x * y;
	case '/':return x / y;
	case '^':return pow(x, y);
	default:return -0x3f3f3f3f;
	}
}
void change(string s)
{
	int len = s.size();
	for (int i = 0; i < len; i++)
	{
		if (isdigit(s[i]))dat.push(s[i]);
		else if (s[i] == '(')op.push(s[i]);
		else if (s[i] == ')')
		{
			char t = op.top();
			while (t != '(')
			{
				op.pop();
				dat.push(t);
				t = op.top();
			}
			op.pop();//要弹出左括号
		}
		else if (check(s[i]) >= 1 && check(s[i]) <= 3)//为运算符
		{
			if (!op.empty())
			{
				char t = op.top();
				while (!op.empty() && check(s[i]) <= check(t))
				{
					if (check(s[i]) == check(t) && s[i] == '^')break;//在s[i]与栈顶都是^号时也能进栈
					op.pop();
					dat.push(t);
					if (!op.empty())t = op.top();
				}
			}
			op.push(s[i]);
		}
	}
	while (!op.empty())
	{
		char t = op.top();
		op.pop();
		dat.push(t);
	}
	while (!dat.empty())
	{
		char t = dat.top();
		dat.pop();
		op.push(t);
	}
	while (!op.empty())
	{
		char t = op.top();
		cout << t << ' ';
		op.pop();
		dat.push(t);
	}
	cout << endl;
}
void calc()
{
	while (!dat.empty())
	{
		char t = dat.top();
		dat.pop();
		op.push(t);
	}
	while (!op.empty())
	{
		char t = op.top();
		op.pop();
		if (isdigit(t))num.push(t - '0');
		else
		{
			int x = num.top();
			num.pop();
			int y = num.top();
			num.pop();
			num.push(js(y, x, t));//传参数时要把x和y反过来
			while (!num.empty())
			{
				int t = num.top();
				num.pop();
				dat2.push(t);
			}
			while (!dat2.empty())
			{
				int t = dat2.top();
				cout << t << ' ';
				dat2.pop();
				num.push(t);
			}
			while (!op.empty())
			{
				char t = op.top();
				cout << t << ' ';
				op.pop();
				dat.push(t);
			}
			while (!dat.empty())
			{
				char t = dat.top();
				dat.pop();
				op.push(t);
			}
			cout << endl;
		}
	}
}
int main()
{
	string s;
	cin >> s;
	change(s);
	calc();
	return 0;
}

5.机器翻译 

https://www.luogu.com.cn/problem/P1540

import java.util.*;

/**
 * Author : yjy
 * Desc
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        int[] arr = new int[M];
        for(int i=0;i<M;i++){
            arr[i] = sc.nextInt();
        }
        int res = 0;
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < M; i++) {
            if(queue.contains(arr[i])){
                continue;
            }
            else{
                if(queue.size()==N){
                    queue.poll();
                }
                queue.offer(arr[i]);
                res++;
            }
        }
        System.out.println(res);
    }
}

 

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int n, m, x, ans, l, r, a[1005], b[1005];
int main()
{
	cin >> m >> n;
	l = 0, r = 0;//初始化两个指针
	for (int i = 1; i <= n; i++) {
		scanf("%d", &x);//边读边做
		if (a[x] == 0) {//没有被访问过
			ans++;
			r++;
			b[r] = x; a[x] = 1;
			if (r > m) {
				l++; a[b[l]] = 0;
			}
		}
	}
	cout << ans;
	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1796499.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

docker构建java项目镜像

资料参考 参考自黑马教程&#xff1a;10.Docker基础-自定义镜像_哔哩哔哩_bilibili 初步准备 打包好java项目jar包&#xff0c;和Dockerfile文件一起放到指定目录下&#xff0c;后续操作都是在该目录下操作&#xff0c; 我这边是&#xff1a;/usr/local/src/train-ticket/ …

IDEA破解后的配置

以下所有操作都要求进入全局setting而不是某一个项目的setting 进入全局Setting File→close project 进入欢迎页面 低版本 然后点击Setting 关闭自动更新 不关闭有可能会破解失败 Appearance & Behavior->System Settings->Updates下取消Automatically chec…

【网络编程开发】6.UDP通信

6.UDP通信 UDP实现框架 send 函数 原型&#xff1a; #include <sys/socket.h> ssize_t send(int sockfd, const void *buf, size_t len, int flags);功能&#xff1a; send 函数的主要功能是向指定的套接字发送数据。 参数&#xff1a; sockfd&#xff1a;一个有效的套…

【Linux】进程(7):地址空间

大家好&#xff0c;我是苏貝&#xff0c;本篇博客带大家了解Linux进程&#xff08;7&#xff09;&#xff1a;地址空间&#xff0c;如果你觉得我写的还不错的话&#xff0c;可以给我一个赞&#x1f44d;吗&#xff0c;感谢❤️ 目录 &#xff08;A&#xff09; 直接看代码&…

Leetcode3169. 无需开会的工作日

Every day a Leetcode 题目来源&#xff1a;3169. 无需开会的工作日 解法1&#xff1a;排序 遍历 按 LeetCode56.合并区间 的做法&#xff0c;把 meetings 数组中所有重叠的区间合并起来&#xff0c;再统计其中无需开会的工作日个数。 代码&#xff1a; /** lc appleetco…

学习笔记——路由网络基础——缺省(默认)路由

3、缺省(默认)路由 1、定义 缺省路由(默认路由)&#xff1a;是目的地址和掩码都为全0的特殊路由。全0代表任意网络。缺省路由在路由表中的形式为&#xff1a;0.0.0.0/0缺省路由也被叫默认路由。缺省路由优先级比直连路由低 缺省路由是一种特殊的路由&#xff0c;当报文没有在…

cv2.imwrite路径中存在中文时出现乱码问题

cv2.imwrite(path, img) 在写入包含中文的路径的时候&#xff0c;保存的文件名称为乱码。 解决办法&#xff1a; cv2.imwrite(path,image)将上面的代码修改为以下代码&#xff0c;可以避免出现中文乱码。 cv2.imencode(.jpg, image)[1].tofile(path)

嵌入式Linux系统编程 — 2.2 标准I/O库:检查或复位状态

目录 1 检查或复位状态简介 2 feof()函数 2.1 feof()函数简介 2.2 示例程序 3 ferror()函数 4 clearerr()函数 4.1 clearerr()函数简介 4.2 示例程序 1 检查或复位状态简介 调用 fread() 函数读取数据时&#xff0c;如果返回值小于参数 nmemb 所指定的值&#xff0c;这…

python常见数据分析函数

apply DataFrame.apply(func, axis0, broadcastFalse, rawFalse, reduceNone, args(), **kwds) 第一个参数是函数 可以在Series或DataFrame上执行一个函数 支持对行、列或单个值进行处理 import numpy as np import pandas as pdf lambda x: x.max()-x.min()df pd.DataFrame(…

【数据结构】详解堆的基本结构及其实现

文章目录 前言1.堆的相关概念1.1堆的概念1.2堆的分类1.2.1小根堆1.2.2大根堆 1.3堆的特点堆的实用场景 2.堆的实现2.1初始化2.2插入2.3堆的向上调整2.4删除2.5堆的向下调整2.6判空2.7获取堆顶元素2.8销毁 3.堆排序3.1实现3.2堆排序的时间复杂度问题 前言 在上一篇文章中&#…

【数据库】SQL零基础入门学习

人不走空 &#x1f308;个人主页&#xff1a;人不走空 &#x1f496;系列专栏&#xff1a;算法专题 ⏰诗词歌赋&#xff1a;斯是陋室&#xff0c;惟吾德馨 目录 &#x1f308;个人主页&#xff1a;人不走空 &#x1f496;系列专栏&#xff1a;算法专题 ⏰诗词歌…

如何通过 4 种方式备份和恢复Android联系人

毫无疑问&#xff0c;联系人是Android手机上存储的最重要的信息之一。为了保护这些重要数据&#xff0c;明智的做法是对Android手机进行联系人备份。如果您的手机发生任何情况导致数据丢失&#xff0c;例如被盗、系统崩溃或物理损坏&#xff0c;您可以再次将备份中的联系人恢复…

Typecho:简约而强大的开源PHP博客平台

Typecho&#xff1a;让博客写作回归本质- 精选真开源&#xff0c;释放新价值。 概览 Typecho是一个开源的PHP博客平台&#xff0c;以其简洁的界面和强大的功能&#xff0c;为博客作者提供了一个高效、易于管理的写作环境。它是一个轻量级、高性能的解决方案&#xff0c;适用于…

主流数据库的大数据插入对比(mssql[sql server]、oracle、postgresql、mysql、sqlite)

首先申明&#xff0c;做这个对比不代表数据库性能&#xff0c;纯属好奇。勿喷&#xff0c;感谢。 测试连续11次插入数据库&#xff0c;每次100万行数据。 测试环境&#xff1a;单机测试&#xff0c;就是所有数据库都装在本机上。操作系统:windows server 2016&#xff0c;使用…

【YOLOV8】1.开发环境搭建

Yolo8出来一段时间了,包含了目标检测、实例分割、人体姿态预测、旋转目标检测、图像分类等功能,所以想花点时间总结记录一下这几个功能的使用方法和自定义数据集需要注意的一些问题,本篇是第一篇,开发环境的配置。 YOLO(You Only Look Once)是一种流行的物体检测和图像分割…

工控主板分类详解

1.ATX系列 尺寸305*244mm;接口扩展丰富,更多的内存和PCIE插槽; 进一步略小的有MATX,尺寸244*244cm;扩展插槽缩减,但兼容ATX接口,依旧是按照ATX标准 2.ITX系列 尺寸170*170mm;相较于ATX主板更加迷你,功能接口也少一些; 常用于小型计算机或者嵌入式系统 高能计算机推…

【Pycharm】功能介绍

1.Code Reformat Code 格式化代码&#xff0c;可以帮助我们去自动调整空格等&#xff0c;根据python语法规范自动调整 2.Settings 1.创建py文件默认填充模版 3.读写py文件编码格式一致性 顶部代码指定的编码方式作用&#xff1a; 可以保证python2/3解释器在读取文件的时候按…

将HTML页面中的table表格元素转换为矩形,计算出每个单元格的宽高以及左上角坐标点,输出为json数据

export function huoQuTableElement() {const tableData []; // 存储表格数据的数组let res [];// 获取到包含表格的foreignObject元素const foreignObject document.getElementById(mydctable);if (!foreignObject){return ;}// 获取到表格元素let oldTable foreignObject…

python tk实现标签切换页面

import tkinter as tk from tkinter import ttk# 初始化主窗口 root tk.Tk() root.title("标签页示例")# 设置窗口大小 root.geometry("400x300")# 创建 Notebook 小部件 notebook ttk.Notebook(root) notebook.pack(expandTrue, fill"both")#…

【leetcode面试经典150题】-45. 跳跃游戏 II

【leetcode面试经典150题】-45. 跳跃游戏 II 1 题目介绍2 个人解题思路2.1 代码 3 官方题解3.1 代码 1 题目介绍 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说&#xff0c;如果你在 nums[i] …