Least Prefix Sum

By xiaruize

分析

M=i=1maiM=\sum\limits^{m}_{i=1}a_i , Sk=i=1kaiS_k=\sum\limits^{k}_{i=1}a_i

Sk<MS_k<M 时,分两类考虑

  1. k<mk<m

    此时,对 a1aka_1 \cdots a_k 执行题目所述的操作,都会同时使 SkS_kMM 增加 , 不会使得当前局面合法

    那么只会对 ak+1ama_{k+1} \cdots a_m 这些数执行操作

    考虑怎样操作最优,容易发现,可以贪心的选择尽可能大的数进行操作

    每次操作会使 M=Max×2M=M-a_x\times 2

  2. k>mk>m

    同上分析,可以发现,这次的操作对象为 am+1aka_{m+1} \cdots a_k , 优先选择小的数进行操作

实现

mm 开始,倒序循环至 11 ,用 priority_queue 维护最大值

同理,再从 mnm \to n 正序循环 ,维护最小值

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Name:
Author: xiaruize
Date:
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define ALL(a) (a).begin(), (a).end()
#define pb push_back
#define mk make_pair
#define pii pair<int, int>
#define pis pair<int, string>
#define sec second
#define fir first
#define sz(a) int((a).size())
#define rep(i, x, y) for (int i = x; i <= y; i++)
#define repp(i, x, y) for (int i = x; i >= y; i--)
#define Yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define No cout << "No" << endl
#define NO cout << "NO" << endl
#define debug(x) cerr << #x << ": " << x << endl
#define double long double
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int N = 2e5 + 10;

// bool st;
int t;
int n, m;
int a[N];
// bool en;

void solve()
{
int res = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
int sum = 0;
for (int i = 1; i <= m; i++)
sum += a[i];
int tot = 0;
tot = sum - a[m];
priority_queue<int> q;
q.push(a[m]);
for (int i = m - 1; i >= 1; i--)
{
if (tot < sum)
{
while (tot < sum)
{
sum -= q.top() * 2ll;
q.pop();
res++;
}
}
q.push(a[i]);
tot -= a[i];
}
priority_queue<int, vector<int>, greater<int>> p;
tot = sum;
for (int i = m + 1; i <= n; i++)
{
p.push(a[i]);
tot += a[i];
if (tot < sum)
{
while (tot < sum)
{
tot -= p.top() * 2ll;
p.pop();
res++;
}
}
}
cout << res << endl;
}

signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
// cerr<<(&en-&st)/1024.0/1024.0<<endl;
// auto t_1=chrono::high_resolution_clock::now();
cin >> t;
while (t--)
solve();
// auto t_2=chrono::high_resolution_clock::now();
// cout <<". Elapsed (ms): " << chrono::duration_cast<chrono::milliseconds>(t_2 - t_1).count() << endl;
return 0;
}