a373中等座標壓縮・前進圖 DP 與樹狀陣列
APCS 2024/10:搭到終點 (ZeroJudge o714)
依路線終點排序,快速加總可以搭乘該路線的所有到達方式。
這題在學什麼
每次乘車都前進,所以抵達終點 e 的最後一條路線 [s,e],前一位置必定滿足 s≤x<e。令 ways[x] 是抵達 x 的方式數,該路線的貢獻就是這段半開區間的 ways 總和;不同路線編號分別計算,即使起終點完全相同也要各貢獻一次。初始 ways[0]=1。
只會在 0 與路線終點下車,把這些位置及 m 排序壓縮。以終點由小到大處理路線,用樹狀陣列查詢 [s,e) 的總和,再把貢獻加入 ways[e]。相同終點的路線先共同查詢再一起更新,清楚確保本批次不把 e 當成可以原地上車的前一位置。
所有轉移從較小座標到較大座標,因此目前查詢使用的值已經完成,不會被未來路線改動。所有加法都對 p 取餘數,最後讀出 ways[m];p=1 時結果自然為 0。
Step-by-step animation
第一個公開範例:終點 4、6、6、7、9,模數 11
步驟 1 / 3
初始與終點 4
ways[0]=1;路線 [0,4] 產生 ways[4]=1。
0:1
4:1
6:0
7:0
9:0
- 已處理終點
- 4
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, destination;
long long mod;
cin >> n >> destination >> mod;
vector<int> start(n), finish(n), coords{0, destination};
for (int &x : start)
cin >> x;
for (int &x : finish) {
cin >> x;
coords.push_back(x);
}
sort(coords.begin(), coords.end());
coords.erase(unique(coords.begin(), coords.end()), coords.end());
vector<pair<int, int>> routes;
for (int i = 0; i < n; ++i)
if (start[i] < finish[i])
routes.emplace_back(finish[i], start[i]);
sort(routes.begin(), routes.end());
vector<long long> bit(coords.size() + 1);
auto add = [&](int index, long long value) {
for (int i = index + 1; i < (int)bit.size(); i += i & -i)
bit[i] = (bit[i] + value) % mod;
};
auto prefix = [&](int count) {
long long result = 0;
for (int i = count; i > 0; i -= i & -i)
result = (result + bit[i]) % mod;
return result;
};
add(0, 1 % mod);
for (int i = 0; i < (int)routes.size();) {
int j = i, e = routes[i].first;
int endIndex = lower_bound(coords.begin(), coords.end(), e) - coords.begin();
long long total = 0, beforeEnd = prefix(endIndex);
while (j < (int)routes.size() && routes[j].first == e) {
int left = lower_bound(coords.begin(), coords.end(), routes[j].second) - coords.begin();
total = (total + beforeEnd - prefix(left) + mod) % mod;
++j;
}
add(endIndex, total);
i = j;
}
int index = lower_bound(coords.begin(), coords.end(), destination) - coords.begin();
cout << (prefix(index + 1) - prefix(index) + mod) % mod << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。