https://codeforces.com/contest/1197/problem/C
You are given a sorted array ?1,?2,…,?? (for each index ?>1 condition ??≥??−1 holds) and an integer ?.
You are asked to divide this array into ? non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let ???(?) be equal to the maximum in the ?-th subarray, and ???(?) be equal to the minimum in the ?-th subarray. The cost of division is equal to ∑?=1?(???(?)−???(?)). For example, if ?=[2,4,5,5,8,11,19] and we divide it into 3 subarrays in the following way: [2,4],[5,5],[8,11,19], then the cost of division is equal to (4−2)+(5−5)+(19−8)=13.
Calculate the minimum cost you can obtain by dividing the array ? into ? non-empty consecutive subarrays.
Input
The first line contains two integers ? and ? (1≤?≤?≤3⋅105).
The second line contains ? integers ?1,?2,…,?? (1≤??≤109, ??≥??−1).
Output
Print the minimum cost you can obtain by dividing the array ? into ? nonempty consecutive subarrays.
Examples
inputCopy
6 3
4 8 15 16 23 42
outputCopy
12
inputCopy
4 4
1 3 3 7
outputCopy
0
inputCopy
8 1
1 1 2 3 5 8 13 21
outputCopy
20
Note
In the first test we can divide array ? in the following way: [4,8,15,16],[23],[42].
题目大意:分为m组,m组的花费为m组最大元素减去最小元素的差。求把n个数分为m组的最小花费。
1.普通写法
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<stack>
#include<string>
#define ll long long
#define rep(i,a,b)for(int i=a;i<=b;i++)
#define rep1(i,a,b)for(int i=a;i<b;i++)
#define rep2(i,a,b)for(int i=a;i>=b;i--)
#define rep3(i,a,b)for(int i=a;i>b;i--)
using namespace std;
const int maxn=3e5+10;
int n,m;
ll arr[maxn],ans[maxn];
int main(){
while(~scanf("%d%d",&n,&m)){
rep(i,1,n)
scanf("%lld",&arr[i]);
rep(i,2,n){
ans[i]=arr[i-1]-arr[i];
//printf("%lld\n",ans[i]);
}
sort(ans+2,ans+n+2);
ll sum=arr[n]-arr[1];
rep(i,2,m){
sum+=ans[i];
//printf("%lld\n",sum);
}
printf("%lld\n",sum);
}
return 0;
}
``
```2.用vector,避免开数组出现wa
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<set>
#include<stack>
#include<string>
#include<vector>
#define ll long long
#define rep(i,a,b)for(int i=a;i<=b;i++)
#define rep1(i,a,b)for(int i=a;i<b;i++)
#define rep2(i,a,b)for(int i=a;i>=b;i--)
#define rep3(i,a,b)for(int i=a;i>b;i--)
using namespace std;
int n,m;
int main(){
while(~scanf("%d",&n,&m)){
vector<int>diff(n);
rep1(i,0,n)
scanf("%d",diff[i]);
vector<int>ans;
rep1(i,1,n){
ans.push_back(diff[i-1]-diff[i]);
}
sort(ans.begin(),ans.end());
int sum=diff[n-1]-diff[0];
rep1(i,0,m-1)
sum+=ans[i];
printf("%d\n",sum);
}
return 0;
}