排序法
用排序法常见的情况是输入一个包含几个(一般一到两个)权值的数组,通过排序然后遍历模拟计算的方法求出最优值。
有些题的排序方法非常显然,如 「USACO1.3」修理牛棚 Barn Repair 就是将输入数组差分后排序模拟求值。
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main() {
ios::sync_with_stdio(false);
int m, s, c;
cin >> m >> s >> c;
int* cc = new int[c];
for (int i = 0; i < c; i++) {
cin >> cc[i];
}
if(m>c){
cout<<c<<endl;
return 0;
}
sort(cc, cc + c);
int ans=cc[c-1]-cc[0]+1;
int* b = new int[c];
for(int i = 0; i < c; i++){
b[i] = cc[i+1]-cc[i];
}
sort(b,b+c-1,cmp);
for (int i = 0; i < m-1; i++)
{
ans=ans-b[i]+1;
}
cout<<ans<<endl;
//system("pause");
}
京公网安备 11010502036488号