CF940E Cashback solution

This question seems to be very annoying. At first glance, I really didn't have any ideas.

But after careful analysis of the topic, we will find:

  • c = 1 c=1 c=At 1 , the answer is 0, but it seems that there is no such point?
  • c > n c > n c>When n , the answer is the sum of the sequence.
  • c = n c = n c=When n , the answer is the sum of the sequence minus the minimum value.
  • 1 < c < n 1 < c < n 1<c<n n < 2 × c n < 2 \times c n<2×At c , the sequence can only be divided into one segment at this time, and other sequences can be regarded as intervals of length 1.
  • 1 < c < n 1 < c < n 1<c<n 2 × c ≤ n 2 \times c \leq n 2×cAt n , we can divide the sequence into multiple segments, while other sequences can still be divided into intervals of length 1.

So there are only two intervals: length 1 and length ccc

Next, we mainly consider 1 <c <n 1 <c <n1<c<n 's situation.

We found that at this time the problem has become a dp problem.

Setting fi f_ifiMeans to ai a_iai The answer at the deadline, then:

  • 1 ≤ i < c 1 \leq i < c 1i<c 时: f i = ∑ j = 1 i a j f_i = \sum_{j = 1}^{i}a_j fi=j=1iaj
  • c ≤ i ≤ n c \leq i \leq n cin 时: f i = min ⁡ ( f i − c + s u m i − s u m i − c − m i n n i , f i − 1 + a i ) f_i = \min{(f_{i - c} + sum_i - sum_{i - c} - minn_i,f_{i - 1} +a_i)} fi=min(fic+sumisumicminni,fi1+ai)

Explanation: sum sums u m is the prefix and the array,minni minn_iminniDisplay [i − c + 1, i] [i --c + 1, i][ic+1,i ] The minimum value in this interval.

Wait: the minimum value of a fixed interval? Isn't this what monotonous queues do!

So monotonic queue O (n) O(n)O ( N ) Resolutionminni minn_iminni, After that O (n) O (n)O ( n ) dp is fine.

Total complexity O (n) O(n)O ( n )

Code:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MAXN = 1e5 + 10;
int n, c, q[MAXN], l = 1, r = 0;
LL a[MAXN], f[MAXN], minn[MAXN], sum[MAXN];

LL read()
{
    
    
	LL sum = 0, fh = 1; char ch = getchar();
	while (ch < '0' || ch > '9') {
    
    if (ch == '-') fh = -1; ch = getchar();}
	while (ch >= '0' && ch <= '9') {
    
    sum = (sum << 3) + (sum << 1) + (ch ^ 48); ch = getchar();}
	return sum * fh;
}

int main()
{
    
    
	n = read(), c = read();
	for (int i = 1; i <= n; ++i) a[i] = read();
	for (int i = 1; i <= n; ++i)
	{
    
    
		while (l <= r && q[l] + c <= i) l++;
		while (l <= r && a[i] <= a[q[r]]) r--;
		q[++r] = i; minn[i] = a[q[l]]; sum[i] = sum[i - 1] + a[i];
	}
	for (int i = 1; i < c; ++i) f[i] = f[i - 1] + a[i];
	for (int i = c; i <= n; ++i) f[i] = min(f[i - c] + sum[i] - sum[i - c] - minn[i], f[i - 1] + a[i]);
	printf("%lld\n", f[n]);
	return 0;
}

Guess you like

Origin blog.csdn.net/BWzhuzehao/article/details/112280299