a286中等加權完成時間・相鄰交換證明
TOI 2025/04 潛力組:建築物拆除
以工期與每日罰金的交叉乘積決定拆除順序。
解題思路
建築 i 在完成當天仍罰款,若它在第 Cᵢ 天完成,總罰金就是 aᵢ×Cᵢ;目標為所有加權完成時間總和。沒有理由空等,因為所有罰金均為正,提早開始只會降低成本。
比較相鄰兩棟 i、j,假設前面已耗時 t。i 先做的貢獻為 aᵢ(t+bᵢ)+aⱼ(t+bᵢ+bⱼ),j 先做則為 aⱼ(t+bⱼ)+aᵢ(t+bⱼ+bᵢ),差是 aⱼbᵢ−aᵢbⱼ。因此當 bᵢaⱼ≤bⱼaᵢ 時應讓 i 在前。按此比較器排序可消除所有逆序,相鄰交換不增加成本,得到全域最佳;比例相等時任意先後都同成本。
Step-by-step animation
範例依 (a,b) 排為 (6,1)、(4,2)、(1,3)
步驟 1 / 3
先拆每日罰金 6 的建築
花 1 天,在第 1 天完成,貢獻 6×1=6。
(6,1)
(4,2)
(1,3)
- 累積天數
- 1
- 罰金
- 6
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Building {
long long a, b;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<Building> v(n);
for (auto &x : v)
cin >> x.a >> x.b;
sort(v.begin(), v.end(),
[](const Building &x, const Building &y) { return x.b * y.a < y.b * x.a; });
long long time = 0, answer = 0;
for (auto x : v) {
time += x.b;
answer += x.a * time;
}
cout << answer << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。