CF 612C. Replace To Make Regular Bracket Sequence【括号匹配】
2024-08-27 19:54:26
【链接】:CF
【题意】:给你一个只含有括号的字符串,你可以将一种类型的左括号改成另外一种类型,右括号改成另外一种右括号
问你最少修改多少次,才能使得这个字符串匹配,输出次数
【分析】:
本题用到了栈。如果遇上左括号,就加进栈里。如果遇上右括号,就判断栈里的左括号是否和它匹配,不匹配就加一。不论匹不匹配,判断后都要让左括号出栈。
如果最后栈不为空,或者栈在循环结束前就为空,那么不论怎么改变,左右括号都不可能刚好匹配。
【代码】:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<utility>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#include<iterator>
#include<stack>
using namespace std;
typedef __int64 LL;
const int INF=1e9+7;
const double eps=1e-7;
const int maxn=1000000;
char s[maxn+10];
int n;
bool isle(char x)
{
return x=='('||x=='<'||x=='['||x=='{';
}
int cal(char x,char y)
{
if(x=='('&&y==')') return 0;
if(x=='['&&y==']') return 0;
if(x=='{'&&y=='}') return 0;
if(x=='<'&&y=='>') return 0;
return 1;
}
int work()
{
n=strlen(s+1);
stack<int>st;
int ans=0;
for(int i=1;i<=n;i++)
{
char x=s[i];
if(isle(x)) st.push(i);
else
{
if(st.empty()) return -1;
int y=st.top();
st.pop();
ans+=cal(s[y],s[i]);
}
}
if(!st.empty()) return -1;
return ans;
}
int main()
{
while(~scanf("%s",s+1))
{
int ans=work();
if(~ans) printf("%d\n",ans);
else puts("Impossible");
}
return 0;
}
最新文章
- CloudNotes之桌面客户端篇:插件系统的实现
- VS2010,Qt插件安装使用
- Flume采集处理日志文件
- html5移动端Meta设置
- mac os x用macport安装redis
- SharePoint咨询师之路:设计之前的那些事一:容量
- js模仿jquery里的几个方法parent, parentUntil, children
- doubango(6)--Doubango协议栈中对RTP的管理
- CentOS 7 校对时间 修改时区
- 自动微分方法(auto diff)
- Spring @AfterReturning 总是返回null
- Wireshark抓包分析TCP 3次握手、4次挥手过程
- MySQL之IDE工具介绍及数据备份
- [Web]flask-excel实现excel文件下载的前后端实现
- 【Linux】【GIt】Linux下安装和配置Git(转)
- 叠加dgv中相同的行信息
- C 编译过程浅析
- [转]关于Json格式
- gradle结合spring-boot生成可运行jar包,并打印日志
- atan2 atan
热门文章
- Java IO 之 FileFilter与FilenameFilter
- 如何在自家厨房里制作LSD
- JQuery选择器$()的工作原理浅析
- 2016广东工业大学校赛 D题 GDUT-oj1172
- 第五届华中区程序设计邀请赛暨武汉大学第十四届校赛 网络预选赛 A
- poj1185 炮兵阵地 状压dp
- bzoj 5093 [Lydsy1711月赛]图的价值 NTT+第二类斯特林数
- 编程技巧 - malloc()与free()
- Spring Boot(一)
- Join to domain powershell script