AcWing 2003. 找到牛!
题意
给定一个括号字符串,连续的两个'('可以表示牛的前脚,连续的两个')'可以表示牛的后脚,前脚必须在后脚的左侧,求牛的可能位置有几个,牛的可能位置由他的前后脚表示。
数据范围
解题思路
-
正解是的做法,记一下当前位置及以前的"(("的对数,判断当前位置是否为"))",如果是"))",答案加上之前的"(("数量。
-
我的做法是处理出来所有的"(("和"))"的位置,前者是记录第二个字符的位置,后者记录第一个字符的位置,然后枚举左括号的位置,二分查找可以与之匹配的右括号数量,加到答案上。但该方法复杂度为,且边界容易出错。
代码
方法一:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 5e4 + 10;
char s[N];
int main()
{
scanf("%s", s);
int n = strlen(s);
int cnt = 0, ans = 0;
for(int i = 1; i < n; i ++){
if(s[i] == '(' && s[i - 1] == '(') cnt ++;
if(s[i] == ')' && s[i - 1] == ')') ans += cnt;
}
printf("%d\n", ans);
return 0;
}
方法二:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 5e4 + 10;
char s[N];
int l[N], r[N];
int main()
{
scanf("%s", s);
int n = strlen(s);
int idxl = 0, idxr = 0;
for(int i = 1; i < n; i ++){
if(s[i] == '(' && s[i - 1] == '(') l[idxl ++] = i;
}
for(int i = n - 2; i >= 0; i --){
if(s[i] == ')' && s[i + 1] == ')') r[idxr ++] = i;
}
sort(r, r + idxr);
int ans = 0;
for(int i = 0; i < idxl; i ++){
int x = l[i];
int ll = 0, rr = idxr - 1;
while(ll < rr){
int mid = ll + rr + 1 >> 1;
if(r[mid] <= x) ll = mid;
else rr = mid - 1;
}
if(r[ll] > x) ans += idxr - ll;
else ans += idxr - ll - 1;
}
printf("%d\n", ans);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架