版本比较
oute
标题
增加 1 行删除 1 行
11题解:P17639 [ICPC 2019 Yinchuan R] Delivery Routeoute正文
增加 3 行删除 142 行
112334567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431445# [ICPC 2019 Yinchuan R] Delivery Route 题解
[双倍经验!](https://www.luogu.com.cn/problem/P3008)
## 题意
在一个图中有 $x$ 条双向边道路和 $y$ 条单向边航线,道路边权非负,充电轨道可能可能存在负权边,求 $s$ 到每个点的最短路或输出无解。
## 解法
### 思路
注意到带负权边,无法直接利用 Dijkstra 求解,也不能用 SPFA,因为会被卡。
注意到对于道路的边权非负,我们可以将图分成只由道路组成的块,然后在块中跑 Dijkstra。对于块间,我们可以将块缩成点后,发现充电轨道保证不能反向联通,所以缩点后的图是一个 DAG。由此而来,我们可以用拓扑排序来确定更新答案的顺序。
### 具体步骤
1. 将由道路构成的图记为 $G_1$,由充电轨道构成的图记为 $G_2$。2. 利用 DFS 在 $G_1$ 中划分连通块,记录每个点所属的块 $belong_u$ 和每块的点集 $block_b$。3. 遍历 $G_2$ 的所有边,若两端点属于不同块,则在块间图 $G_3$ 中加边,并统计入度 $indeg$。4. 对 $G_3$ 进行拓扑排序,得到处理顺序。5. 按拓扑序处理每个块: - 将块内所有已有距离的点加入优先队列; - 在块内跑 Dijkstra(只走 $G_1$ 的边); - 块内 Dijkstra 结束后,用 $G_2$ 的边更新其他块的距离。6. 输出结果,不可达输出 `NO PATH`。
## 代码
时间复杂度:$O((n+x+y)\log n)$。空间复杂度:$O(n+x+y)$。
```cpp#include<bits/stdc++.h>using namespace std;using ll=long long;const int maxn=25005,INF=2e9+1;int n,x,y,s;vector<pair<int,int>> g1[maxn],g2[maxn];//int belong[maxn],b_siz;vector<int> block[maxn];void dfs(int u,int b){ belong[u]=b; block[b].push_back(u); for(auto e:g1[u]){ int v=e.first; if(!belong[v]) dfs(v,b); }}//-vector<pair<int,int>> g3[maxn];vector<int> topu;int indeg[maxn];void Topu(){ int m=b_siz; queue<int> q; for(int u=1;u<=m;u++){ if(indeg[u]==0) q.push(u); } while(!q.empty()){ int u=q.front(); q.pop(); topu.push_back(u); for(auto e:g3[u]){ int v=e.first; if(--indeg[v]==0) q.push(v); } }}//-int dis[maxn];void dij(){ fill(dis,dis+n+1,INF); dis[s]=0; for(int b:topu){ priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq; for(int u:block[b]) if(dis[u]!=INF) pq.push({dis[u],u}); while(!pq.empty()){ int d=pq.top().first,u=pq.top().second; pq.pop(); if(d>dis[u]) continue; for(auto e:g1[u]){ int v=e.first,w=e.second; if(dis[v]>dis[u]+w){ dis[v]=dis[u]+w; pq.push({dis[v],v}); } } } for(int u:block[b]){ for(auto e:g2[u]){ int v=e.first; int w=e.second; if(dis[u]!=INF&&dis[v]>dis[u]+w){ dis[v]=dis[u]+w; } } } }}int main(){ ios::sync_with_stdio(false);cin.tie(0); cin>>n>>x>>y>>s; for(int i=1;i<=x;i++){ int a,b,c; cin>>a>>b>>c; g1[a].push_back({b,c}),g1[b].push_back({a,c}); } for(int i=1;i<=y;i++){ int a,b,c; cin>>a>>b>>c; g2[a].push_back({b,c}); } for(int i=1;i<=n;i++){ if(belong[i]==0) dfs(i,++b_siz); } for(int i=1;i<=n;i++){ for(auto e:g2[i]){ int v=e.first; if(belong[v]!=belong[i]) g3[belong[i]].push_back({belong[v],e.second}),indeg[belong[v]]++; } } Topu(); dij(); for(int i=1;i<=n;i++){ if(dis[i]==INF){ cout<<"NO PATH"<<endl; }else{ cout<<dis[i]<<endl; } } return 0;}/*6 3 3 41 2 5 3 4 55 6 103 5 -100 4 6 -100 1 3 -10*/```[](https://www.luogu.com.cn/problem/P1001)