题意
要给所有糖葫芦按顺序裹上糖浆,前提是糖葫芦长度不大于糖浆的量,此时糖浆量 。
对于糖浆不够的锅,可以进行合并,但会损失掉 的糖浆,问最少的合并次数。
Solution
由于糖葫芦是固定顺序的,那么一定是对糖浆锅排序,对于每个糖葫芦组,二分恰好满足她的长度,从这个锅开始往后的所有锅都满足了她的长度,只需要个数足够即可,每个糖浆量为 的锅可以满足长度 的糖葫芦 次,且结束后变为 ,由于待修改,我们要用 。
考虑样例 1 的最后一组,两个 3 平摊一次 任务,枚举是不好的,不妨把相同大小的合并为一个点,于是 更好,则一个大小为 的点可以贡献 次任务,如果这个点抗住了这一次,那么将分裂为两组,一组是 ,一组为原来的,小心处理余数即可,反之把这一组用完继续处理下一组即可。
如果搞到最后失败了,即 还有剩余,我们写一个函数用于处理合并。
具体的,合并也像刚才那样,每一组看合并几个,小心处理余数,自行模拟即可。
由于分裂产生的节点个数顶多到 ,因此复杂度 。
代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,x,y) for(int i=x;i<=y;i++)
#define per(i,x,y) for(int i=x;i>=y;i--)
const int N = 5e5+5;
int koishi, satori;
int n, m, k;
map<int, int> mp;
int ans = 0;
vector<pair<int, int>>in;
bool merge(int b, int c) {
if (mp.empty()) {
cout << -1 << '\n';
return false;
}
auto it = mp.end();
it--;
int x0 = it->first;
int cnt0 = it->second;
if (cnt0 == 1) mp.erase(it);
else mp[x0]--;
int res = 0;
int ned = b + c - 1;
while (x0 < ned) {
if (mp.empty()) {
cout << -1 << '\n';
return false;
}
auto it = mp.end();
it--;
int y = it->first;
int cnty = it->second;
if (y <= k) {
cout << -1 << '\n';
return false;
}
int dif = y - k;
int nw = (ned - x0 + dif - 1) / dif;
if (nw <= cnty) {
res += nw;
x0 += nw * dif;
if (nw == cnty) mp.erase(it);
else mp[y] -= nw;
break;
} else {
res += cnty;
x0 += cnty * dif;
mp.erase(it);
}
}
if (x0 - c > 0) mp[x0 - c] += 1;
ans += res;
return true;
}
void solve() {
cin >> n >> m >> k;
mp.clear();
ans = 0;
rep(i, 1, n) {
int x;
cin >> x;
mp[x]++;
}
in.clear();
rep(i, 1, m) {
int b, c;
cin >> b >> c;
in.push_back({b, c});
}
for (auto [b, c] : in) {
auto it = mp.lower_bound(b);
while (it != mp.end() && c > 0) {
int x = it->first, cnt = it->second;
int ok = x - b + 1;
int tot = ok * cnt;
if (c >= tot) {
c -= tot;
it = mp.erase(it);
if (b - 1 > 0) {
mp[b - 1] += cnt;
}
} else {
int full = c / ok;
int rem = c % ok;
int ned = full + (rem > 0 ? 1 : 0);
mp[x] -= ned;
if (mp[x] == 0) mp.erase(it);
if (full > 0 && b - 1 > 0) mp[b - 1] += full;
if (rem > 0) mp[x - rem] += 1;
c = 0;
break;
}
}//需要合并
if (c > 0) if (!merge(b, c)) return;
}
cout << ans << '\n';
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// freopen("tanghulu.in", "r", stdin);
// freopen("tanghulu.out", "w", stdout);
cin >> koishi >> satori;
while (satori--) solve();
return 0;
}