[ICPC 2019 Yinchuan R] Delivery Route 题解
题意
在一个图中有 条双向边道路和 条单向边航线,道路边权非负,充电轨道可能可能存在负权边,求 到每个点的最短路或输出无解。
解法
思路
注意到带负权边,无法直接利用 Dijkstra 求解,也不能用 SPFA,因为会被卡。
注意到对于道路的边权非负,我们可以将图分成只由道路组成的块,然后在块中跑 Dijkstra。对于块间,我们可以将块缩成点后,发现充电轨道保证不能反向联通,所以缩点后的图是一个 DAG。由此而来,我们可以用拓扑排序来确定更新答案的顺序。
具体步骤
- 将由道路构成的图记为 ,由充电轨道构成的图记为 。
- 利用 DFS 在 中划分连通块,记录每个点所属的块 和每块的点集 。
- 遍历 的所有边,若两端点属于不同块,则在块间图 中加边,并统计入度 。
- 对 进行拓扑排序,得到处理顺序。
- 按拓扑序处理每个块:
- 将块内所有已有距离的点加入优先队列;
- 在块内跑 Dijkstra(只走 的边);
- 块内 Dijkstra 结束后,用 的边更新其他块的距离。
- 输出结果,不可达输出
NO PATH。
代码
时间复杂度:。空间复杂度:。
#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 4
1 2 5
3 4 5
5 6 10
3 5 -100
4 6 -100
1 3 -10
*/