Stable Groups(贪心)

该代码实现了解决一个计算机科学问题的算法,问题要求将数字序列分成组,确保相邻数字之差小于给定值x,且可以用k个任意数字。算法首先对序列排序,然后计算相邻元素的差分,并根据差分判断需要新增组的数量,以满足条件。
摘要由CSDN通过智能技术生成

Problem - 1539C - Codeforces

Stable Groups - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

将n个数分组 ,使得每个组中相邻的两个数之间的差小于x,有k个任意数可以使用,最少只需多少组就可以分完所有数
#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <set>
#define x first
#define y second
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;

typedef pair<int,int> PII;
typedef pair<char,int> PCI;
typedef long long LL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N=2e5+10,INF = 1e9 ;
const double eps = 1e-7;


LL n,k,x;
LL a[N];
LL b[N];
void solve()
{
    cin >> n >> k >> x;
    LL cnt =1; // 刚开始只有一个组 
    for(int i=1;i<=n; i++ ) cin >> a[i];
    
    sort(a+1,a+n+1);
    
    for(int i=2;i<=n;i ++)
    b[i-1] = a[i] - a[i-1 ];
    
    sort(b+1,b+n);
    
    for(int i=1;i<n;i ++ )
    if(b[i] > x )
    {
        // b[i] <= x ===> b[i] < x + 1 == b[i] - x < x 的情况就不用k 
        if(k >= (b[i] - 1 ) /x ) 
        k -= (b[i] - 1) /x ;// 每隔x个位置放一个新的人 
        else cnt ++ ;
    }
    cout << cnt  << endl;
}

int main()
{
//    freopen("1.txt","r",stdin);
    ios 
    LL T=1;
//     cin>>T;
    while(T -- )
    {
        solve();
    }    
    
    
    
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值