一.
题意: 问只移动一个括号,是否可以使这个序列合法
分析: ( 相当于1,)相当于-1; 在读入时,统计前缀和sum,如果,合法的序列,‘( ’ 与 ‘ )’会相互抵消。假若sum出现过<-1 的情况,即代表有超过一个的‘ )’没有得到匹配,所以,只移动1个括号是不可能使它合法。
如果最后的sum!=0,代表 ‘( ’ 与 ‘ )’的个数不相等,肯定不合法。
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<cmath>
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
char str[maxn];
int main()
{
int n;
scanf("%d",&n);
scanf("%s",str);
int sum = 0,flag=0;
for(int i=0;i<n;i++)
{
if(str[i]=='(') sum++;
else sum--;
if(sum<-1) flag=1;
}
if(sum!=0) flag=1;
if(flag==0) puts("YES");
else puts("NO");
return 0;
}
二.
牛客集训营4-B
题意: 有 [ , ] , { , } , ( , ) 六种符号,问给出的序列是否合法
分析: 用vector ,大体思路就是 每放入vector中一个字符,就与上一个字符进行判断,如果是一对,那就用两个vec.pop_back();删掉这一对字符,不是就不用管了,接着输下一个字符, 输入的字符是‘\n’ 就代表字符串输入完了, 然后判断vector是否为空集就可以了
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<cmath>
#define mod 1000000007
using namespace std;
typedef long long ll;
int main()
{
vector<char>a;
char x;
ll len=0;
scanf("%c",&x);
a.push_back(x);
scanf("%c",&x);
while(x!='\n')
{
a.push_back(x);
len=a.size();
if(a[len-2]=='['&&x==']')
{
a.pop_back();
a.pop_back();
}
else if(a[len-2]=='('&&x==')')
{
a.pop_back();
a.pop_back();
}
else if(a[len-2]=='{'&&x=='}')
{
a.pop_back();
a.pop_back();
}
scanf("%c",&x);
}
if(!a.empty())cout<<"No"<<endl;
else cout<<"Yes"<<endl;
return 0;
}
三.
题目:
合法括号序列的定义是:
1.空序列是合法括号序列
2.如果 S 是一个合法括号序列,那么(S)是合法括号序列
3.如果 A 和 B 都是合法括号序列,那么 AB 是一个合法括号序列
现在给定一个括号序列,求最少删去几个括号能得到一个合法的括号序列
输入包含 T 组数据,每组数据中,设括号序列的长度为 N
1≤T,ΣN≤1,000,000
(由于空串是合法的括号序列,所以答案可以是N)
只有 ( ,)两种符号
分析: 与上一题思路一样,最后输出集合的大小
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<cmath>
#define mod 1000000007
using namespace std;
typedef long long ll;
int main()
{
int t;
cin>>t;
while(t--)
{
vector<char>a;
char x;
ll len,n;
cin>>n;
getchar();
scanf("%c",&x);
while(x!='\n')
{
a.push_back(x);
len=a.size();
if(len>=2)
{
if(x==')'&&a[len-2]=='(')
{
a.pop_back();
a.pop_back();
}
}
//cout<<a.size()<<endl;
scanf("%c",&x);
}
cout<<a.size()<<endl;
}
return 0;
}