3016: [Usaco2012 Nov]Clumsy Cows

Description

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:
)(
())(
((())))
 
問題描述
給定長度爲n的一個括號序列,每次修改可以修改一個位置的括號,若這個括號爲’(‘,則修改爲’)’,若這個括號爲’)’,則修改爲’(‘,問最少修改多少個使得原括號序列合法。
其中:
     ()是合法的;
     A是合法的,則(A)是合法的;
     AB都是合法的,則AB是合法的。
 

Input

 一個長度爲n個括號序列。
 

Output

 
最少的修改次數。
 

Sample Input

())(

Sample Output

2
樣例說明
修改爲()(),其中紅色部分表示修改的括號。

數據範圍
100%的數據滿足:1 <= n <= 100,000。

HINT

Source

Silver

題解:

  這題直接亂搞。。我們知道,對於每個合法的括號序列,這個序列的任意一個位置的之前的所有的左括號的數目都是要大於等於右括號的數目的。所以我們利用這條性質,可以用一個計數器來模擬一個類似單調棧的東西,每次進來一個右括號,都用它來抵消左括號,當計數器等於0,即相當於所有的左括號都匹配了一個右括號的時候,又來了一個右括號,那麼這時就需要改變括號。最後的答案要再加上多出來的左括號的數目的一半。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN=10001;
int main(int argc, char *argv[])
{
	int d=0,n,i;
	int ans=0;
	char x;
	while(cin>>x)
	{
		if(x=='(') d++; 
		else if(x==')'&&d>=1) d--;
		else if(x==')'&&d==0) ans++,d++;
	}
	ans+=(d+1)/2;
	printf("%d\n",ans);
	return 0;
}


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