【CodeForces - 1197C】Array Splitting(水题)
題干:
You are given a?sorted?array?a1,a2,…,ana1,a2,…,an?(for each index?i>1i>1?condition?ai≥ai?1ai≥ai?1holds) and an integer?kk.
You are asked to divide this array into?kk?non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let?max(i)max(i)?be equal to the maximum in the?ii-th subarray, and?min(i)min(i)?be equal to the minimum in the?ii-th subarray. The cost of division is equal to?∑i=1k(max(i)?min(i))∑i=1k(max(i)?min(i)). For example, if?a=[2,4,5,5,8,11,19]a=[2,4,5,5,8,11,19]?and we divide it into?33?subarrays in the following way:?[2,4],[5,5],[8,11,19][2,4],[5,5],[8,11,19], then the cost of division is equal to?(4?2)+(5?5)+(19?8)=13(4?2)+(5?5)+(19?8)=13.
Calculate the minimum cost you can obtain by dividing the array?aa?into?kk?non-empty consecutive subarrays.
Input
The first line contains two integers?nn?and?kk?(1≤k≤n≤3?1051≤k≤n≤3?105).
The second line contains?nn?integers?a1,a2,…,ana1,a2,…,an?(1≤ai≤1091≤ai≤109,?ai≥ai?1ai≥ai?1).
Output
Print the minimum cost you can obtain by dividing the array?aa?into?kk?nonempty consecutive subarrays.
Examples
Input
6 3 4 8 15 16 23 42Output
12Input
4 4 1 3 3 7Output
0Input
8 1 1 1 2 3 5 8 13 21Output
20Note
In the first test we can divide array?aa?in the following way:?[4,8,15,16],[23],[42][4,8,15,16],[23],[42].
題目大意:
給一個有序數組(n=3e5),分成K份,要求每份的最大值減最小值的差最小,求這個差值。
解題報告:
? ?化簡個公式然后求相鄰點的差的最小值就可以了。取前k-1個,拿個優先隊列維護一下。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define F first #define S second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 4e5 + 5; int a[MAX],n,k; priority_queue<int> pq; ll ans; int main() {cin>>n>>k;for(int i = 1; i<=n; i++) cin>>a[i];for(int i = 2; i<=n; i++) pq.push(a[i] - a[i-1]);for(int i = 1; i<=k-1; i++) ans -= pq.top(),pq.pop();ans += a[n]-a[1];cout << ans << endl;return 0 ; }?
總結
以上是生活随笔為你收集整理的【CodeForces - 1197C】Array Splitting(水题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡逾期怎么办 及时补救是上策
- 下一篇: 信用卡逾期怎么贷款 “连三累六”很可怕