跳到正文

个人记录

题解:P17639 [ICPC 2019 Yinchuan R] Delivery Route

niuniudundun约 5 分钟
原文

这是 2026年11月5日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月7日
收录
2026年11月5日
更新
2026年11月17日
篇幅
约 5 分钟
题目
P17639

版本

  1. v2当前
  2. v1

[ICPC 2019 Yinchuan R] Delivery Route 题解

双倍经验!

题意

在一个图中有 xx 条双向边道路和 yy 条单向边航线,道路边权非负,充电轨道可能可能存在负权边,求 ss 到每个点的最短路或输出无解。

解法

思路

注意到带负权边,无法直接利用 Dijkstra 求解,也不能用 SPFA,因为会被卡。

注意到对于道路的边权非负,我们可以将图分成只由道路组成的块,然后在块中跑 Dijkstra。对于块间,我们可以将块缩成点后,发现充电轨道保证不能反向联通,所以缩点后的图是一个 DAG。由此而来,我们可以用拓扑排序来确定更新答案的顺序。

具体步骤

  1. 将由道路构成的图记为 G1G_1,由充电轨道构成的图记为 G2G_2。
  2. 利用 DFS 在 G1G_1 中划分连通块,记录每个点所属的块 belongubelong_u 和每块的点集 blockbblock_b。
  3. 遍历 G2G_2 的所有边,若两端点属于不同块,则在块间图 G3G_3 中加边,并统计入度 indegindeg。
  4. 对 G3G_3 进行拓扑排序,得到处理顺序。
  5. 按拓扑序处理每个块:
    • 将块内所有已有距离的点加入优先队列;
    • 在块内跑 Dijkstra(只走 G1G_1 的边);
    • 块内 Dijkstra 结束后,用 G2G_2 的边更新其他块的距离。
  6. 输出结果,不可达输出 NO PATH。

代码

时间复杂度:O((n+x+y)log⁡n)O((n+x+y)\log n)。空间复杂度:O(n+x+y)O(n+x+y)。

C++
#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
*/