洛谷 P1209 [USACO1.3]修理牛棚 Barn Repair题解

题目

打死我也没想到是贪心

虽然是lkx写了贪心题解让我去点赞我才写的这道题

神仙思路

首先排好序

假设我们现在只有一块木板

我们做一个差分数组

对这个差分数组排序之后

一次断开最长的区间

m-1次之后

便可以得到最小的啦

需要注意的是

此题有坑点需要特判提供的木板数比牛棚数还多的情况

那种情况直接就输出牛棚的数量就好啦

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 2100;
int cow[N], m, s, c, cf[N], ans;
int read() {
    int s = 0, w = 1;
    char ch = getchar();
    while(!isdigit(ch)) {if(ch == '-') w = -1; ch = getchar();}
    while(isdigit(ch)) {s = s * 10 + ch - '0'; ch = getchar();}
    return s * w;
}
bool cmp(int x, int y) {
    return x > y;
}
int main() {
    m = read(), s = read(), c = read();
    for(int i = 1; i <= c; i++) cow[i] = read();
    if(m > c) {
        printf("%d\n", c);
        return 0;
    }
    sort(cow + 1, cow + 1 + c);
    ans = cow[c] - cow[1] + 1;
    for(int i = 2; i <= c; i++) cf[i] = cow[i] - cow[i - 1];
    sort(cf + 2, cf + c + 1, cmp);
    for(int i = 2; i <= m; i++) 
        ans = ans - cf[i] + 1;
    printf("%d\n", ans);
    return 0;
        
        
}

谢谢收看,祝身体健康!

猜你喜欢

转载自www.cnblogs.com/yanxiujie/p/11713771.html
今日推荐