题目链接:http://codeforces.com/contest/918/problem/C
知识点: 贪心
解题思路:
枚举起点(当起点就是\(')'\)时直接跳过)并在此基础上遍历字符串,用一个\(nowmin\)和一个\(nowmax\)来记录当前\('('\)最多有\(nowmax\)个,最少有\(nowmin\)个。当遍历到\('('\)时,\(nowmin++,nowmax++\);当遍历到\('?'\)时,\(nowmin--,nowmax++\)(因为\('?'\)既有可能是\('('\),也有可能是\(')'\));当遍历到\(')'\)时,\(nowmin++,nowmax++\)。当\(nowmax<0\)时就可以结束对这个起点的字符串的遍历,当\(nowmin<0\)时将其置零,当\(nowmin==0\)并且\(nowmax>=0\)并且当前遍历长度为偶数时,答案数加一。
思路来自magicalCycloidea.
AC代码:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 const int maxn = 5005; 5 char inp[maxn]; 6 int main() 7 { 8 scanf("%s",inp); 9 int len=strlen(inp); 10 int ans=0; 11 for(int i=0;i<len;i++){ 12 if(inp[i]==')') continue; 13 int nowmin=0,nowmax=0; 14 for(int j=i,l=1;j<len;j++,l++){ 15 if(inp[j]=='(') nowmax++,nowmin++; 16 else if(inp[j]=='?') nowmax++,nowmin--; 17 else nowmax--,nowmin--; 18 if(nowmax<0) break; 19 nowmin=max(0,nowmin); 20 if(l%2==0&&nowmin==0&&nowmax>=0) ans++; 21 } 22 } 23 printf("%d\n",ans); 24 return 0; 25 }