【acwing】2003. 找到牛(思维)

穿越隧道
在这里插入图片描述

O(n)

只扫一遍,后腿数量加上之前前腿出现的位置,就是牛出现的位置的总情况。
参见大佬思路

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 10;
map<pair<pii,pii>,int> mp;
int ans,cnt;
string s;
int main(){
    cin >> s;
    int len = s.size();
    // cout <<"len = " << len << endl;
    for(int i = 0,j = len - 1; i < len; i++){
        
        if(i < len - 1 && s[i] == '(' && s[i + 1] =='('){
            cnt++;//后腿数量增加
        }
        if(i < len - 1 && s[i] == ')' && s[i + 1] == ')'){
            ans+=cnt;//前腿数量ans
            //ans也为牛的位置数量
        }
    }
    // pair<pii,pii> aaa;
    // int bbb = 0;
    // map<pair<pii,pii>,int>::iterator it;
    // for(it = mp.begin(); it!=mp.end(); it++){
    //     aaa = it->first;
    //     bbb = it->second;
    //     cout << aaa.first.first <<" " << aaa.first.second << " || " << aaa.second.first <<" " << aaa.second.second << bbb  << endl;
    // }
    cout << ans << endl;
    return 0;
}

TLE版(5/10)

只能过一半样例
数据范围: 5 e 4 5e^4 5e4

#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 10;
map<pair<pii,pii>,int> mp;
string s;
int main(){
    cin >> s;
    int len = s.size();
    // cout <<"len = " << len << endl;
    for(int i = 0,j = len - 1; i < len; i++){
        if(i < len - 1 && s[i] == '(' && s[i + 1] =='('){
            while(j >= 1 && j > i + 1){
                if(s[j] == ')' && s[j - 1] == ')'){
                    mp[{{i,i+1},{j,j-1}}]++;
                }
                j--;
            }
            j = len - 1;
            // cout <<" i = " << i << endl;
        }
    }
    // pair<pii,pii> aaa;
    // int bbb = 0;
    // map<pair<pii,pii>,int>::iterator it;
    // for(it = mp.begin(); it!=mp.end(); it++){
    //     aaa = it->first;
    //     bbb = it->second;
    //     cout << aaa.first.first <<" " << aaa.first.second << " || " << aaa.second.first <<" " << aaa.second.second << bbb  << endl;
    // }
    cout << mp.size() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值