[codeforces 1374C] Move Brackets 括號()配對

Codeforces Round #653 (Div. 3)   參與排名人數11687

[codeforces 1374C]    Move Brackets    括號()配對

總目錄詳見https://blog.csdn.net/mrcrack/article/details/103564004

在線測評地址http://codeforces.com/contest/1374/problem/C

Problem Lang Verdict Time Memory
C - Move Brackets GNU C++17 Accepted 30 ms 3600 KB

樣例模擬如下:

2
)(

1
位置12
括號)(
l代表未配對的(數量
r代表未配對的)數量

掃描到位置1:l=0,r=1
掃描到位置2:l=1,r=1
需移動1次


4
()()

0
位置1234
括號()()
l代表未配對的(數量
r代表未配對的)數量

掃描到位置1:l=1,r=0
掃描到位置2:l=0,r=0
掃描到位置3:l=1,r=0
掃描到位置4:l=0,r=0
需移動0次


8
())()()(

1
位置12345678
括號())()()(
l代表未配對的(數量
r代表未配對的)數量

掃描到位置1:l=1,r=0
掃描到位置2:l=0,r=0
掃描到位置3:l=0,r=1
掃描到位置4:l=1,r=1
掃描到位置5:l=0,r=1
掃描到位置6:l=1,r=1
掃描到位置7:l=0,r=1
掃描到位置8:l=1,r=1
需移動1次

10
)))((((())

3
位置12345678910
括號)))((((())
l代表未配對的(數量
r代表未配對的)數量

掃描到位置1:l=0,r=1
掃描到位置2:l=0,r=2
掃描到位置3:l=0,r=3
掃描到位置4:l=1,r=3
掃描到位置5:l=2,r=3
掃描到位置6:l=3,r=3
掃描到位置7:l=4,r=3
掃描到位置8:l=5,r=3
掃描到位置9:l=4,r=3
掃描到位置10:l=3,r=3
需移動3次

AC代碼如下:

#include <stdio.h>
char s[55];
int main(){
	int t,n,i,l,r;
	scanf("%d",&t);
	while(t--){
		scanf("%d%s",&n,s);
		l=r=0;
		for(i=0;i<n;i++)
			if(s[i]=='(')l++;
			else if(s[i]==')'){//s[i]==')'
				if(l)l--;//()配對
				else r++;
			}
		printf("%d\n",r);//餘下未配對的)數量
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章