笔试强训Day13 贪心 优先队列

牛牛冲钻五

题目链接:A-牛牛冲钻五_牛客小白月赛38 (nowcoder.com)

思路:

没什么好说的 就是正常思路 写出来即可。

AC code:

#include<string>
#include <iostream>
using namespace std;
int ans;
int cmobo;
int k,n,t;
string a;
int main() 
{
    cin >> t;
    while(t --)
    {
        ans = 0;
        cmobo = 0;
        cin >> n >> k;
        cin >> a;
        for(auto& t : a)
        {
            if(t == 'W')
            {
                cmobo++;
                if(cmobo >= 3)
                    ans += k;
                else
                    ans++;
            }
            else
            {
                cmobo = 0;
                ans--;
            }
        }
        cout << ans << endl;

    }
    return 0;
}

NC41 最长无重复子数组

题目链接:最长无重复子数组_牛客题霸_牛客网 (nowcoder.com)

思路:

用map来实现 类似滑动窗口。注意相同元素多次插入时

AC code:

class Solution {
public:
    int maxLength(vector<int>& arr)
    {
        unordered_map<int, int> mp;
        int res = 0;
        for(int left = 0, right = 0; right < arr.size(); right++)
        {
            mp[arr[right]]++;
            while(mp[arr[right]] > 1)
                mp[arr[left++]]--;
            res = max(res, right - left + 1);
        }
        return res;
    }
};

NC379 重排字符串

题目链接:重排字符串_牛客题霸_牛客网 (nowcoder.com)

思路:

这里没到原题 但是找到了封装接口的,思路都一样。

创建大根堆,优先加上出现次数多的字母即可。

AC code:

#include <iostream>
#include<queue>
#include<string>
using namespace std;
const int N = 200;
typedef pair<int, char> PIC;
priority_queue<PIC, vector<PIC>> q;
priority_queue<PIC, vector<PIC>> p;
string s;
int n;
int a[N];
string ans = "5";
int main()
{
    cin >> n >> s;
    for (auto& t : s)
        a[t]++;

    for (int i = 0; i < 199; i++)
        if (a[i] != 0)
            q.push({ a[i],i });

    if (q.size() == 1)
    {
        cout << "no";
        return 0;
    }
    while (q.size())
    {
        if (q.size() == 1 && q.top().first > 1)
        {
            cout << "no";
            return 0;
        }
        while (ans.back() == q.top().second)
        {
            auto t = q.top();
            q.pop();
            p.push(t);
        }
        auto t = q.top();
        q.pop();
        ans += t.second;
        t.first--;
        if (t.first)
            q.push(t);
        while (p.size())
        {
            auto t = p.top();
            p.pop();
            q.push(t);
        }
    }
    cout << "yes" << endl;
    for (int i = 1; i < ans.size(); i++)
        cout << ans[i];
    return 0;
}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值