洛谷 P4447 [AHOI2018初中组]分组

题目链接:

[AHOI2018初中组]分组 - 洛谷https://www.luogu.com.cn/problem/P4447

思路:

贪心思路,如果能插入之前的组,就插入之前的组,并且贪心地选择尽可能短的组插入,如果实在没有可插入的组,就新开一组。

代码:

#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e5+5;
int n;
int arr[maxn];
int last[maxn];
int len[maxn];

int main(){
	cin >> n;
	for(int i=1; i<=n; i++){
		cin >> arr[i];
	}
	sort(arr+1, arr+n+1); //先放小的,再放大的,必须排序
	int size = 0; //分组后的队列大小
	for(int i=1; i<=n; i++){
		bool find = false;
		int minIdx;
		int minLen = inf;
		for(int j=1; j<=size; j++){
			if(last[j]+1 == arr[i] && len[j] < minLen){
				minLen = len[j];
				minIdx = j;
				find = true;
			}
		}
		if(find){
			last[minIdx] = arr[i];
			len[minIdx]++;
		}
		else{
			last[++size] = arr[i];
			len[size] = 1;
		}
	}
	int ans = inf;
	for(int i=1; i<=size; i++){
		if(len[i] < ans) ans = len[i];
	}
	cout << ans << '\n';
	return 0;
}

队友的代码,他用优先队列解决,当前数字如果能插入其他组,必定是插入末尾数字最大的队列(但是对于连续的相同的数字有例外,所以多开了个队列处理特殊情况),他的做法复杂度是O(nlogn)

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

struct point
{
    int number, x;
    bool operator<(const point y) const
    {
        if (y.x == x)
            return number > y.number;
        else
            return x < y.x;
    }
};

int main()
{
    int n, a[100010], ans = 1 << 30;
    point temp;
    priority_queue<point, vector<point>, less<point>> que;
    priority_queue<point, vector<point>, less<point>> que2;
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> a[i];
    sort(a, a + n);

    for (int i = 0; i < n; i++)
    {
        point t;
        if (i && a[i] > a[i - 1])
        {
            while (!que2.empty())
            {
                que.push(que2.top());
                que2.pop();
            }
        }
        if (!que.empty() && que.top().x == a[i] - 1) //能放进之前的组
        {
            t = que.top();
            que.pop();
            t.x++;
            t.number++;
            que2.push(t);
        }
        else //必须新开一组
        {
            t.number = 1;
            t.x = a[i];
            que.push(t);
        }
    }
    while (!que2.empty())
    {
        que.push(que2.top());
        que2.pop();
    }
    while (!que.empty())
    {
        temp = que.top();
        ans = min(ans, temp.number);
        que.pop();
    }
    cout << ans << "\n";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值