洛谷 P4447分组

贪心简单题

思路

大致想法是用一个队列记录当前正在进行中分组的起始位置,并记录当前分组数,若扫描到的下一个数的个数少于当前分组数,则代表当前有一定数量的分组需要就此停止,按照开始顺序依次出队列即可

代码

#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <cmath>
#include <stack>
#include <map>
#include <algorithm>
#include <climits>
#include <queue>
using namespace std;




int main()
{
    int n;
    cin >> n;
    map<int,int> store;
    for(int i = 0;i < n;i++)
    {
        int k;
        scanf("%d",&k);
        store[k]++;
    }
    int res = INT_MAX;
    int num = 0;//表示当前分组数量
    queue<int> record;
    int i = 0;
    for(map<int,int> :: iterator it = store.begin();it!=store.end();i++)
    {
        int q = it->second;
        int now = it->first;
        if(q > num)
            for(int j = 0;j < q - num;j++)
                record.push(i);
        else if(q < num)
            for(int j = 0;j < num - q;j++)
            {
                int m = record.front();
                record.pop();
                res = min(res, i - m);
            }

        num = q;
        ++it;
        if(it == store.end())
        {
            while(!record.empty())
            {
                res = min(res,i+1-record.front());
                record.pop();
            }
            break;
        }

        if(it->first - now!=1)
        {
            num = 0;
            while(!record.empty())
            {
                res = min(res,i+1-record.front());
                record.pop();
            }

        }
    }
    cout << res << endl;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值