Codeforces Round #459 (Div. 2) C-The Monster (贪心)
【题意】
给定(,),? 问号可代替( 或 ) 问能匹配多少个()
【思路】
O(n^2) 枚举边, 用 T 表示 ( 的数量 用cnt 记录 ? 的数量, 先把? 看做 )
遇到 ( T++
遇到 ) T--
遇到 ? T-- ,cnt++
当T=0 说明 可以比配一个( )
当 T<0, cnt >0 说明 ? 此时可以代替 ( 处理, 所以 T+=2 相当于两个 (,cnt--;
当 T<0 cnt < 0 说明 无法匹配 break
【代码实现】
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { string str; int ans=0; cin>>str; int t=0,cnt=0; int len=str.length(); for(int i=0;i<len;i++) { t=0,cnt=0; for(int j=i;j<len;j++) { if(str[j]=='(') t++; else if(str[j]==')') t--; else t--,cnt++; if(t==0) ans++; else if(t<0&&cnt>0) { t+=2; cnt--; } else if(t<0&&cnt<=0) break; } } cout<<ans<<endl; return 0; }
1
岂曰无衣?与子同袍。王于兴师,修我戈矛。与子同仇!
岂曰无衣?与子同泽。王于兴师,修我矛戟。与子偕作!
岂曰无衣?与子同裳。王于兴师,修我甲兵。与子偕行!