解題思路
前緣嚴格增加,所以只可能是0或某個服務右端。壓縮這些座標並按右端遞增處理服務。要啟用 [l,r],前一個前緣 f 必須在 [l−1,r−1],故取該範圍所有狀態的最低費用及對應方案總數,再加服務費。
線段樹保存「較小費用優先、同費用相加」的摘要。相同右端的服務不能互相接續,查詢上界必須嚴格小於 r。每個有效序列有唯一最後服務編號,因此候選計數相加恰好涵蓋全部最優序列。正費用與嚴增前緣亦保證無法重用同服務。
時間 O(m log(m+1)),空間 O(m),含 Python 排序、座標及讀取緩衝;N≤10^9 不能建立大小 N 的表。
Step-by-step animation
逐步教學推演:依各步描述的例子觀察狀態、轉移與答案。
步驟 1 / 3
起始前緣
N=3,服務[1,1]費2、[2,3]費4、[1,3]費7。
0
- 最低費用
- 0
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
using P = pair<ll, ll>;
const ll INF = 4e18;
P mg(P a, P b) {
if (a.first != b.first)
return min(a, b);
return {a.first, (a.second + b.second) % MOD};
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, m;
cin >> N >> m;
vector<array<int, 3>> e(m);
vector<int> x{0};
for (auto &a : e) {
cin >> a[0] >> a[1] >> a[2];
x.push_back(a[1]);
}
sort(x.begin(), x.end());
x.erase(unique(x.begin(), x.end()), x.end());
sort(e.begin(), e.end(), [](auto a, auto b) { return a[1] < b[1]; });
int S = 1;
while (S < (int)x.size())
S *= 2;
vector<P> t(2 * S, {INF, 0});
auto up = [&](int i, P v) {
i += S;
t[i] = mg(t[i], v);
while (i /= 2)
t[i] = mg(t[2 * i], t[2 * i + 1]);
};
auto qu = [&](int l, int r) {
P a = {INF, 0};
for (l += S, r += S; l < r; l /= 2, r /= 2) {
if (l & 1)
a = mg(a, t[l++]);
if (r & 1)
a = mg(a, t[--r]);
}
return a;
};
up(0, {0, 1});
for (auto [l, r, w] : e) {
int j = lower_bound(x.begin(), x.end(), r) - x.begin(),
i = lower_bound(x.begin(), x.end(), l - 1) - x.begin();
auto [d, c] = qu(i, j);
if (d < INF)
up(j, {d + w, c});
}
int j = lower_bound(x.begin(), x.end(), N) - x.begin();
auto [d, c] = j < (int)x.size() && x[j] == N ? qu(j, j + 1) : P{INF, 0};
cout << (d == INF ? -1 : d) << ' ' << c << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。