简化题意
给定一个有 个点 条边的无向图。每条边的边权为一个二元组 ,求从 到其他所有点的最短路。
其中 到 的路径权值记为 。
题目分析
最短路。
考虑单源最短路(这里说的是 dijkstra)的步骤:找到一个有效的点 ,然后对它周围的点进行遍历,如果满足三角不等式(),那么更新 且入优先队列。
但是对于这道题,我们发现,我们并不知道哪些点会满足三角形不等式。换言之,我们不知道当前这个点是否应该入队。但是我们可以发现下面的性质:
对于点 ,设可以到达 的路径集合为 ,当前有到 的路径长度 。
,则 一定不满足三角不等式。
,则 一定满足三角不等式。
这样,我们可以对每个点搞一个 set,在里面存上每个到这个点的路径权值。然后每当得到一个新的长度,就去里面查一查,看看满不满足即可。
感觉复杂度有点玄学,可能是因为数据太弱了。如果数据加强了,我立即删题解。
参考代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <ctime>
#include <set>
#define itset set<PLL>::iterator
using namespace std;
using LL = long long;
using PII = pair<int, int>;
using PLL = pair<LL, LL>;
const int N = 2010, M = N << 1;
const LL INF = 1e12;
LL dist[N]; int n, m;
set<PLL> s[N];
bool st[N];
namespace Edges {
int h[N], e[M], ne[M], idx; PLL w[M];
void add(int a, int b, LL w1, LL w2) {
e[ ++ idx] = b, ne[idx] = h[a], h[a] = idx;
w[idx] = {w1, w2};
}
} using namespace Edges;
struct Node {
int ver; LL a, b;
bool operator < (const Node &tmp)const {
return tmp.a * tmp.b < a * b;
}
};
bool check(int u, LL a, LL b) {
itset it = s[u].upper_bound({a, b});
if (it != s[u].begin()) {
it -- ;
if (it -> second < b) return false;
}
return true;
}
void dij() {
priority_queue<Node, vector<Node>> q;
fill(dist + 1, dist + n + 1, INF);
s[1].insert({0, 0}); dist[1] = 0;
q.push({1, 0, 0});
while (q.size()) {
auto t = q.top(); q.pop();
int ver = t.ver, a = t.a, b = t.b;
for (int i = h[ver]; i; i = ne[i]) {
int j = e[i];
if (!check(j, a + w[i].first, b + w[i].second)) continue;
s[j].insert({a + w[i].first, b + w[i].second});
dist[j] = min(dist[j], (a + w[i].first) * (b + w[i].second));
q.push({j, a + w[i].first, b + w[i].second});
}
}
}
int main() {
scanf("%d%d", &n, &m);
while (m -- ) {
int a, b; LL w1, w2;
scanf("%d%d%lld%lld", &a, &b, &w1, &w2);
add(a, b, w1, w2), add(b, a, w1, w2);
}
dij();
for (int i = 2; i <= n; i ++ )
printf("%lld\n", dist[i] == INF ? -1 : dist[i]);
return 0;
}