【CodeForces - 940E】Cashback(set+DP)
阿新 • • 發佈:2018-02-27
except best ++ -c subarray nload () 最小 cpp ?=?2 is 3?+?6?+?5?=?14.
Description
Since you are the best Wraith King, Nizhniy Magazin ?Mir? at the centre of Vinnytsia is offering you a discount.
You are given an array a of length n and an integer c.
The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3,?1,?6,?5,?2] with c
Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.
Solution
這裏有一個貪心的思想,就是只需要劃分長度為1或者長度為c的區間,其他的不會比這兩種更優
首先裸的DP,\(dp[i]=min\{dp[j]+Cost_{j+1,i}\}\)
然後只要對長度為c的區間進行更新,可以用multiset進行存儲數據
(STL中的multiset與set的區別在於可以存儲相同的元素)
具體見代碼
Code
#include <cstdio>
#include <algorithm>
#include <set>
#define ll long long
#define N 100010
using namespace std;
int n,c;
ll A[N],dp[N],sum;
multiset<ll> q;//默認升序排列
int main(){
scanf("%d%d",&n,&c);
for(int i=1;i<=n;i++)scanf("%I64d" ,&A[i]);
for(int i=1;i<=n;i++){
sum+=A[i];
dp[i]=dp[i-1]+A[i];
q.insert(A[i]);
if(i>c){q.erase(q.find(A[i-c]));sum-=A[i-c];}//刪除最小的元素
if(i>=c){dp[i]=min(dp[i],dp[i-c]+sum-*q.begin());}//轉移
}
printf("%I64d\n",dp[n]);
return 0;
}
【CodeForces - 940E】Cashback(set+DP)