[CodeForces] [612C] Replace To Make Regular Bracket Sequence

Problem Description

Loading...

Problem Analysis

The problem asks for the number of changes needed to turn the string into a valid bracket sequence
A left (right) bracket must be changed into another left (right) bracket
If it cannot be modified, output “Impossible”

PS:
Cases such as {(}) also need modifications (2 times)
So simply push a left bracket onto the stack when encountered
For a right bracket, check whether it matches the top of the stack
If not, modify it

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<cstdio>
#include<stack>
#include<cstring>
using namespace std;
char s[1000200];
bool cmp(char a,char b) {
	if((a=='['&&b==']')||(a=='('&&b==')')||(a=='{'&&b=='}')||(a=='<'&&b=='>'))
		return true;
	else
		return false;
}
int main() {
	while(scanf("%s",s)!=EOF) {
		stack<char>a;
		int l=strlen(s);
		int cnt=0;
		bool flag=true;
		for(int i=0; i<l; i++) {
			if(s[i]=='['||s[i]=='<'||s[i]=='{'||s[i]=='(')
				a.push(s[i]);
			else if(s[i]==']'||s[i]=='>'||s[i]=='}'||s[i]==')') {
				if(a.empty()) {
					flag=false;
					break;
				} else if(!cmp(a.top(),s[i])) {
					cnt++;
				}
				a.pop();
			}
		}
		if(!a.empty())
			flag=false;
		if(flag)
			printf("%d\n",cnt);
		else
			printf("Impossible\n");
	}
	return 0;
}

Problem URL:【CodeForces】[612C]Replace To Make Regular Bracket Sequence

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...