笔试强训Day3 字符串 前缀和 优先队列

BC149 简写单词

题目链接:简写单词_牛客题霸_牛客网 (nowcoder.com)

思路:先将所有输入的字母大写 遍历一遍若某个字母前面为 '  ', 则尾加进答案字符串。

AC 代码:

#include<string>
#include <iostream>
using namespace std;
string a;
string ans = "";
int main()
{
    getline(cin, a);

    for(int i = 0; i < a.size(); i ++)
        a[i] = toupper(a[i]);
    
    ans += a[0];

    for(int i = 1; i < a.size(); i ++)
        if(a[i - 1] == ' ') ans += a[i];

    cout << ans << endl;

    return 0;
}

dd爱框框

题目链接:F-dd爱框框_牛客小白月赛34 (nowcoder.com)

思路:数组长度 1e7 , 时间限制 2s 应采用时间复杂度O(N) 或 O(NlogN)以下的算法。由于l 到 r 连续,故可采用前缀和预处理 双指针加减距离操作解题。

AC 代码:

#include <iostream>
using namespace std;
typedef pair<int,int> PII;
typedef long long LL;
const int N = 1e7 + 10;
PII ans = {-1e9,1e9};
int sum;
int n,x;
int a[N];
LL s[N];
int main() 
{
    cin >> n >> x; 

    for(int i = 1; i <= n; i ++)
    { 
            cin >> a[i];
            s[i] = a[i] + s[i - 1];
    }

    int pos = 0;
    for(int i = 1; i <= n; i ++)
    {
        if(s[i] - s[pos] >= x)
        {
            while(s[i] - s[pos] >= x)
            {
                pos ++;
            }
            if(i - pos < ans.second - ans.first)
            {
                ans.second = i;
                ans.first = pos;
            }
        }
    }
    cout << ans.first << ' ' << ans.second << endl;    
}

除2!

题目链接:A-除2!_牛客挑战赛45 (nowcoder.com)

思路: 需用一个结构将数组中的偶数元素存储 且需多次排序 每次对最大的数进行操作,故可使用优先队列。注意若一个偶数 /2 完成后 若不是偶数 不需再入优先队列。

AC 代码:

#include <iostream>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
typedef long long LL;
int n,k;
int a[N];
LL ans;
priority_queue<int,vector<int>> q;
int main()
{
    cin >> n >> k;
    for(int i = 1; i <= n; i ++)
    {
        int x; cin >> x;
        if(x & 1) ans += x;
        else q.push(x);
    }
    while(k -- && q.size())
    {
        int t = q.top();
        q.pop();
        if( ! (t / 2 & 1) ) q.push(t / 2);
        else ans += t / 2;
    }
    while(q.size())
    {
        int t = q.top();
        q.pop();
        ans += t;
    }

    cout << ans << endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值