Description
Input
Output
Sample Input
Sample Output
HINT
Source
就是一个有负边的最短路, 但是spfa会TLE。那么就得利用这个图的某些特殊性质了。
因为有向边保证不会形成环,整个图就相当于多个块,中间是用有向边连接起来的。块里不存在负边就可以直接堆优化的迪杰斯特拉
块与块之间用拓扑排序解决,也就是有向边只能被用一次。
#includeusing namespace std;inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - 48; ch = getchar(); } return x * f;}const int N = 2e5 + 100;const int INF = 0x3f3f3f3f;struct E { int v, ne, c; } e[N], E[N];struct P { int u, d; bool operator < (const P &rhs) const { return d > rhs.d; } P(int uu, int dd): u(uu), d(dd) {}};int head[N], he[N], cnt, dis[N], cn, q[N], du[N], bel[N];int n, r, p, s, block;vector blo[N];bool vis[N];inline void add(int u, int v, int c) { e[++cnt].v = v; e[cnt].c = c; e[cnt].ne = head[u]; head[u] = cnt;}inline void ad(int u, int v, int c) { E[++cn].v = v; E[cn].c = c; E[cn].ne = he[u]; he[u] = cn;}void dfs(int u, int c) { bel[u] = c; blo[c].push_back(u); for (int i = head[u]; i; i = e[i].ne) { int v = e[i].v; if (bel[v]) continue; dfs(v, c); }}int main() { n = read(), r = read(), p = read(), s = read(); while (r--) { int u = read(), v = read(), c = read(); add(u, v, c); add(v, u, c); } while (p--) { int u = read(), v = read(), c = read(); ad(u, v, c); } for (int i = 1; i <= n; i++) { if (!bel[i]) dfs(i, ++block); } for (int i = 1; i <= n; i++) { for (int j = he[i]; j; j = E[j].ne) { ++du[bel[E[j].v]]; } } int l = 1, r = 0; for (int i = 1; i <= block; i++) { if (!du[i]) q[++r] = i; } priority_queue que; memset(dis, 0x3f, sizeof(dis)); dis[s] = 0; while (l <= r) { int b = q[l++]; for (int i = 0, sz = blo[b].size(); i < sz; i++) { if (dis[blo[b][i]] < INF) { que.push(P(blo[b][i], dis[blo[b][i]])); } } while (!que.empty()) { P p = que.top(); que.pop(); int u = p.u; if (vis[u]) continue; else vis[u] = 1; for (int i = head[u]; i; i = e[i].ne) { int v = e[i].v; if (dis[u] + e[i].c < dis[v]) { dis[v] = dis[u] + e[i].c; que.push(P(v, dis[v])); } } for (int i = he[u]; i; i = E[i].ne) { int v = E[i].v; if (dis[u] + E[i].c < dis[v]) { dis[v] = dis[u] + E[i].c; } } } for (int i = 0, sz = blo[b].size(); i < sz; i++) { for (int j = he[blo[b][i]]; j; j = E[j].ne) { --du[bel[E[j].v]]; if (!du[bel[E[j].v]]) q[++r] = bel[E[j].v]; } } } for (int i = 1; i <= n; i++) { if (dis[i] == INF) puts("NO PATH"); else printf("%d\n", dis[i]); } return 0;}