CF2055E Haystacks
有
更正式地说,移动的描述如下:
选择两个干草堆
注意:在干草堆被清空之前,它没有高度限制,你可以将任意数量的干草捆移动到该干草堆上。
计算确保每个干草堆至少被清空一次所需的最小移动次数,或者报告这不可能。
草堆题。
记
首先我们可以考虑先随便钦定一个操作排列,然后从前往后,清空每一个稻草堆
假如
假如
我们贪心地,会发现把放不下的部分放到最后一堆一定是最优的。
特殊地,考虑最后一堆,最后一堆里面最后会有
不难发现,答案就是
首先把满足
然后我们考虑两个位置
化简得到:
由此可以推出,当
但是直接排序然后暴力并不是对的,因为最后一个数是需要特殊处理的。
因此我们需要枚举最后一位,然后计算最小的答案。
有一种可行的实现方法是,先把序列排序,然后从前往后扫,同时模拟清空的过程,同时在第
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
using std::cin, std::cout;
const int N = 5e5 + 7;
#define int long long
int n, h[N], c[N], d = 0, f = 0, e, g[N];
std::set<std::pair<int, int>> s;
struct o {int a, b;} v[N];
int find(int x) {
static int s[N]; int t = 0;
while(h[x] != x) s[++t] = x, x = h[x];
for(int i = t - 1; i >= 1; --i)
c[s[i]] += c[s[i+1]], h[s[i]] = x;
return x;
}
bool cmp(o p1,o p2){
static auto f = [](o x) {return x.a < x.b ? -1 : x.a > x.b ? 1 : 0;};
return f(p1)!=f(p2) ? f(p1)<f(p2) : f(p1)<=0 ? p1.a<p2.a : p1.b>p2.b;
}
inline void solve() {
f = d = 0, e = 1e18; cin >> n;
for(int i = 1; i <= n; ++i) cin >> v[i].a >> v[i].b, f += v[i].a;
for(int i = 1; i <= n; ++i) h[i] = i, ::c[i] = 0;
std::sort(v + 1, v + n + 1, cmp);
for(int i = 1, sig = 0, c = 0; i <= n; ++i) {
{ auto [a, b] = v[i - 1];
if(a <= sig) sig -= a;
else c += a - sig, sig = 0;
sig += b;
}
auto [a, b] = v[i]; d += a;
if(auto t = s.upper_bound({d, n}); t != s.begin()) {
int j = (--t)->second; ::c[j] += d - t->first;
for(auto p = s.begin(); p != t; ++p)
h[p->second] = j, ::c[p->second] += (d - p->first) - ::c[j];
s.erase(s.begin(), ++t), s.insert({d, j});
}
d -= b;
::c[i] = c, s.insert({sig + d, i});
}
for(auto& [x, y]: s)
g[y] = x - d;
s.clear();
for(int i = 1; i <= n; ++i) {
int j = find(i), c = ::c[i] + (j == i ? 0 : ::c[j]);
if(v[i].a + c <= g[j]) e = std::min(e, f + c);
}
cout << (e == 1e18 ? -1 : e) << "\n";
}
signed main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t; cin >> t; for(; t--; ) solve();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】