1349. 修理牛棚【难度: 中 / 思维 贪心】

在这里插入图片描述
https://www.acwing.com/problem/content/1351/
在这里插入图片描述
然后用一个大根堆,从所有的间隔,依次从堆顶选一个。
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
int a[N],m,s,c;
int main(void)
{
    
    
    cin>>m>>s>>c;
    for(int i=0;i<c;i++) cin>>a[i];
    sort(a,a+c);
    int sum=a[c-1]-a[0]+1;//初始的总的
    priority_queue<int>heap;
    for(int i=1;i<c;i++)
        if(a[i]-a[i-1]) heap.push(a[i]-a[i-1]-1);//存一下所有的间隔
    while(m>1&&heap.size())//减(m-1)次,且还有间隔
    {
    
    
        auto t=heap.top(); heap.pop();
        sum-=t,m--;
    }
    cout<<sum<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_46527915/article/details/121153095