Codeforces Round #459 (Div. 2) C. The Monster
2018-01-30 09:47
459 查看
链接
就是昨晚的cf题。但是自己卡了半天,最后写了个dp也还是逃不过n^3,超时。
但是看到一个很好很好的想法,现在就想记一下而已。没有代码。
对于一个随机序列,我们设置一个l和r
干嘛的?
我们吧“?”先全部看成是“(”或“)”
然后l记录把?看成)后未配对的(的个数
然后r记录把?看成(后未配对的(的个数
来一个双重循环
ans=0;
for()
l=0,r=0;
for()
读到( ,未配对的(数目加1,l++,r++
读到),未配对的(数目减1,l--,r--
读到?,看做),则l--,看做(,则r++;
l<0但r>0的时候,必然是因为把?当成)而导致l<0,所以将一个?从)变成(,l=l+2
r<0则肯定)已经多了。break;跳出循环
l==0的时候就是符合条件的完全配对的情况,ans++
我只能说漂亮!
————————————————————————————————————————
事后补的代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<string>
#include<stack>
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
const int maxn=1e4+5;
const int inf=0x3f3f3f3f;
typedef long long ll;
int main(){
string s;
cin>>s;
int len=s.length();
int ans=0;
for(int i=0;i<len;i++){
int l=0,r=0;
for(int j=i;j<len;j++){
if(s[j]=='('){
l++;
r++;
}
if(s[j]==')'){
l--;
r--;
}
if(s[j]=='?'){
l--;
r++;
}
if(l<0&&r>0) l+=2;
if(r<0) break;
if(l==0) ans++;
}
}
cout<<ans<<endl;
}
就是昨晚的cf题。但是自己卡了半天,最后写了个dp也还是逃不过n^3,超时。
但是看到一个很好很好的想法,现在就想记一下而已。没有代码。
对于一个随机序列,我们设置一个l和r
干嘛的?
我们吧“?”先全部看成是“(”或“)”
然后l记录把?看成)后未配对的(的个数
然后r记录把?看成(后未配对的(的个数
来一个双重循环
ans=0;
for()
l=0,r=0;
for()
读到( ,未配对的(数目加1,l++,r++
读到),未配对的(数目减1,l--,r--
读到?,看做),则l--,看做(,则r++;
l<0但r>0的时候,必然是因为把?当成)而导致l<0,所以将一个?从)变成(,l=l+2
r<0则肯定)已经多了。break;跳出循环
l==0的时候就是符合条件的完全配对的情况,ans++
我只能说漂亮!
————————————————————————————————————————
事后补的代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<string>
#include<stack>
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
const int maxn=1e4+5;
const int inf=0x3f3f3f3f;
typedef long long ll;
int main(){
string s;
cin>>s;
int len=s.length();
int ans=0;
for(int i=0;i<len;i++){
int l=0,r=0;
for(int j=i;j<len;j++){
if(s[j]=='('){
l++;
r++;
}
if(s[j]==')'){
l--;
r--;
}
if(s[j]=='?'){
l--;
r++;
}
if(l<0&&r>0) l+=2;
if(r<0) break;
if(l==0) ans++;
}
}
cout<<ans<<endl;
}
相关文章推荐
- Codeforces Round #459 (Div. 2) C.The Monster【贪心&括号匹配】
- Codeforces Round #459 (Div. 2) C-The Monster (贪心)
- Codeforces Round #459 (Div. 2)C. The Monster
- Codeforces Round #459 (Div. 2)总结
- Codeforces Round #261 (Div. 2)459D. Pashmak and Parmida's problem(求逆序数对)
- Codeforces Round #459 (Div. 2) B. Radio Station STL map的使用
- Codeforces Round #459 (Div. 2)
- Codeforces Round #459 (Div. 2)-D(dfs暴力)
- Codeforces Round #159 (Div. 2)
- Codeforces Round #157 (Div. 2)
- Codeforces Round 313 div2 题解
- Codeforces Round #150 (Div. 1) A
- 【瞎搞】 Codeforces Round 276 DIV 2 C.Bits
- 【Codeforces Round 271 (Div 2)A】【水题】Keyboard 打字列偏移还原原始串
- 【Codeforces Round 274 (Div 2)E】【DP 成段更新 打标记法 滚动数组】Riding in a Lift 乘坐k次电梯避免到达b层的方案数
- Codeforces Round #334 (Div. 2)
- Codeforces Round #362 (Div. 2) C.Lorenzo Von Matterhorn
- codeforces Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) 题解(A-D)
- Codeforces Round #148 (Div. 2)
- 【Codeforces Round 335 (Div 2) C】【贪心 脑洞 有趣排序】Sorting Railway Cars 全排列排序可以提前后提后的最小操作数