当前位置: 首页 > news >正文

CSP/信奥赛C++刷题训练:经典例题 - 栈(1):洛谷P3056 :[USACO12NOV] Clumsy Cows S

CSP/信奥赛C++刷题训练:经典例题 - 栈(1):洛谷P3056 :[USACO12NOV] Clumsy Cows S

在这里插入图片描述

题目描述

Bessie the cow is trying to type a balanced string of parentheses into her new laptop, but she is sufficiently clumsy (due to her large hooves) that she keeps mis-typing characters. Please help her by computing the minimum number of characters in the string that one must reverse (e.g., changing a left parenthesis to a right parenthesis, or vice versa) so that the string would become balanced.

There are several ways to define what it means for a string of parentheses to be “balanced”. Perhaps the simplest definition is that there must be the same total number of ('s and )'s, and for any prefix of the string, there must be at least as many ('s as )'s. For example, the following strings are all balanced:

()
(())
()(()())

while these are not:

)(
())(
((())))

给出一个偶数长度的括号序列,问最少修改多少个括号可以使其平衡。

输入格式

* Line 1: A string of parentheses of even length at most 100,000 characters.

输出格式

* Line 1: A single integer giving the minimum number of parentheses that must be toggled to convert the string into a balanced string.

样例 #1

样例输入 #1

())(

样例输出 #1

2

提示

The last parenthesis must be toggled, and so must one of the two middle right parentheses.

AC代码

#include<bits/stdc++.h>
using namespace std;
string c;
stack<char> s;
int ans=0;
int main(){cin>>c;int n=c.size();for(int i=0;i<n;i++){if(s.size()==0){//如果栈为空 if(c[i]=='('){//左括号入栈 s.push(c[i]);} else{//右括号处理 ans++;//需更改:答案+1 s.push('(');//变成左括号入栈 }}else{//如果栈不为空 if(c[i]=='('){//左括号入栈 s.push(c[i]);} else{//右括号处理 if(s.top()=='('){s.pop();//成对就弹出 } else{ans++;//不成对,需更改:答案+1 s.push('(');//变成左括号入栈 } }} }//最后栈如果不为空,将一半变为右括号 if(!s.empty()) ans+=(s.size()+1)/2;cout<<ans;return 0;
} 

文末彩蛋:

点击王老师青少年编程主页有更多精彩内容

http://www.lryc.cn/news/480492.html

相关文章:

  • WiFi一直获取不到IP地址是怎么回事?
  • 蓝牙BLE开发——iOS 每次写入数据超过200字节报错?
  • Ascend Extension for PyTorch是个what?
  • 学习docker第五弹-----高级篇start-Dockerfile
  • 【Elasticsearch】Elasticsearch集成Spring Boot
  • HarmonyOS 移
  • 跨子网的WinCC客户机/服务器如何实现通讯?
  • java 面向对象高级
  • 递推经典例题 - 爬楼梯
  • OpenCV视觉分析之目标跟踪(12)找到局部的最大值函数meanShift()的使用
  • 《数据治理精选案例集2.0(2024版)》592页PDF(已授权分享)
  • 【51单片机】LED点阵屏 原理 + 使用
  • Java基于SpringBoot+Vue的宠物共享平台的设计与实现(附源码,文档)
  • 【案例】Excel使用宏来批量插入图片
  • 报名开启|开放原子大赛“Rust数据结构与算法学习赛”
  • [翻译] 创始人模式(Founder Mode)
  • 拓扑排序(C++类封装+数组模拟队列和邻接表)
  • FP独立站引流革命:GG斗篷技术解锁流量新策略
  • 管道(Pipes)、过滤器(Filters)和拦截器(Interceptors)
  • uniapp组件样式运行至小程序失效
  • 认识鸿蒙系统
  • Docker Compose部署Rabbitmq(Dockerfile安装延迟队列)
  • 硬件基础06 滤波器——无源、有源(含Filter Solutions、Filter Pro、MATLAB Fdatool)
  • shopify模块新增内容或图片
  • 【EMNLP2024】基于多轮课程学习的大语言模型蒸馏算法 TAPIR
  • 置信传播算法复现
  • 【在Linux世界中追寻伟大的One Piece】poll代码改写
  • C++builder中的人工智能(17):神经网络中的自我规则非单调(Mish)激活函数
  • Java 的 Scanner 类:控制台输入与文件扫描
  • 使用纯HTML和CSS绘制圣诞树:打造网页中的冬日奇景