动态最短路 (path)
题目来源: 年省选集训第二轮 Day 0。
题意
给定 个点 条边的有向无环图(保证所有边 满足 ),其中每条边为黑色或白色。
接下来有 次询问,每次给出两个正整数 和点 :试求将所有黑边权值设为 ,白边设为 , 到 的最短路长度为多少?
对于所有测试点,保证 ,。
| 测试点编号 | 特殊性质 | ||
|---|---|---|---|
| 无 | |||
| 无 | |||
| 无 |
思路
做法
考虑每个点实际上只需要记录两个信息: —— 分别表示经过的黑边的数量 和白边数量 。
那么,如果存储出了所有这些 ,则每次查询的时候对于每个 对应的权值为 ,只需要从这些中取出最小值。
而这样的 有多少个呢?注意到,同样的 只需要记录最小的 ,所以对于每个点只有 个。
综上,时间复杂度为 。
做法
沿用 的做法,考虑答案的形式是 。那么,这实际上对应着 这条直线,而希望截距尽可能小,不难想到最优必然在下凸壳上取到。
经典结论:若干个横纵坐标值域位于 的点,其凸包的点数为 。
【证明】 考虑凸包上相邻两个横坐标相差超过 对,则只有 对;如果相邻两个纵坐标相差超过 对,则只有 对;如果均不超过,则每个至多相差 ,且如果凸包上相邻两条边斜率相同可看作一条边,所以横纵坐标相差的所有可能只有 种,故凸包的点数为 的。
接下来,只需要维护这个下凸包即可,每次相当于合并若干个凸包。不难做到, 的时间复杂度。
【优化 1】:注意到, 是排序的瓶颈,不过由于值域在 可通过桶排轻松去掉。或者是每次合并若干个有序序列,采用归并排序的方式也可做到线性。
【优化 2】:注意到,查询的时候是 的。这很不好,所以考虑可以在凸包上三分 / 二分,即可做到 。
代码
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
using i64 = long long;
using pii = pair<int, int>;
const int maxn = 50005, maxm = 100005;
int n, m, q;
int h[maxn], e[maxm], ne[maxm], w[maxm], idx;
int din[maxn], top;
pii stk[maxn];
std::vector<pii> conv[maxn];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}
int main() {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
cin >> n >> m;
memset(h, -1, sizeof h);
while (m -- ) {
int u, v, c;
cin >> u >> v >> c;
add(u, v, c), din[v] ++;
}
queue<int> Q;
Q.push(1), conv[1].emplace_back(0, 0);
while (Q.size()) {
int u = Q.front();
Q.pop(), top = 0;
sort(conv[u].begin(), conv[u].end());
for (auto [x, y] : conv[u]) {
int t = top - 1;
if (t >= 0 && y >= stk[t].se) continue;
while (t > 0 && (i64)(y - stk[t].se) * (stk[t].fi - stk[t - 1].fi)
<= (i64)(stk[t].se - stk[t - 1].se) * (x - stk[t].fi))
t --, top --;
stk[top ++ ] = {x, y};
}
conv[u].clear();
for (int i = 0; i < top; i ++)
conv[u].push_back(stk[i]);
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
for (auto [x, y] : conv[u])
if (!w[i]) conv[v].emplace_back(x + 1, y);
else conv[v].emplace_back(x, y + 1);
if (!( -- din[v])) Q.push(v);
}
}
cin >> q;
while (q -- ) {
int a, b, x;
cin >> a >> b >> x;
i64 res = 1ll << 60;
for (auto [x, y] : conv[x])
res = min(res, (i64)a * x + (i64)b * y);
cout << res << '\n';
}
return 0;
}