道路与航线

一道类似缩点的好题,先按道路缩点 然后将缩点以后的图按照航线做DAG

在DAG上先跑topsort 在每一个团内部跑dijkstra,同时更新top点 很有意思的一道题目

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 3e5+10;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;

int n,m1,m2,st;

int e[N],ne[N],w[N],h[N],idx;
void add(int a,int b,int c){
	e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx++;
}


int din[N];
int id[N];
vector<int>block[N];
bool df[N];
int cnt;
int dist[N];
bool vis[N];

void dfs(int u,int ids){
	df[u] = true;
	id[u] = ids;
	block[ids].push_back(u);
	
	for(int i=h[u];~i;i=ne[i]){
		int j = e[i];
		if(!df[j])dfs(j,ids);
	} 
}
queue<int>q;
void dijkstra(int ids)
{
	
	priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>heap;
	for(auto &t:block[ids])heap.push({dist[t],t});
	
	
	while(heap.size()){
		
		auto t = heap.top();heap.pop();
		
		int ver = t.second,distance = t.first;
		
		if(vis[ver])continue;
		vis[ver] = true;
		
		for(int i=h[ver];~i;i=ne[i]){
			int j = e[i];
			//cout<<ver<<" "<<" "<<j<<"\n";
			
			if(dist[j]>distance+w[i]){
				dist[j] = dist[ver]+w[i];
				if(id[j]==id[ver]){
					heap.push({dist[j],j});
				}
			}
			if(id[j]!=id[ver]&&(--din[id[j]]==0))q.push(id[j]);
		}
		
		
	}
	
}

void topsort()
{
	
	for(int i=1;i<=cnt;++i)
	 if(!din[i]){q.push(i);}
	memset(dist,0x3f,sizeof dist);
	memset(vis,0,sizeof vis); 
	dist[st] = 0;
	while(q.size()){
		
		auto t = q.front();
		q.pop();
		//cout<<t<<"??\n";
		dijkstra(t);
		
	}
	
	
}

void solve()
{
	cin>>n>>m1>>m2>>st;
	memset(h,-1,sizeof h);
	for(int i=1;i<=m1;i++){
		int a,b,c;cin>>a>>b>>c;
		add(a,b,c),add(b,a,c);
	}
	
	//缩点
	
	for(int i=1;i<=n;i++)if(!df[i])dfs(i,++cnt);

	
	for(int i=1;i<=m2;i++){
		int a,b,c;cin>>a>>b>>c;
		add(a,b,c);
		din[id[b]]++;
	}
	
	topsort();
	
	
	for(int i=1;i<=n;i++)
	 if(dist[i]>0x3f3f3f3f/2)cout<<"NO PATH\n";
	 else cout<<dist[i]<<"\n";
	
	

}

signed main()
{
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int _;
	//cin>>_;
	_ = 1;
	while(_--)solve();
	return 0;
}
相关推荐
皮卡蛋炒饭.几秒前
宽搜bfs与深搜dfs
算法·宽度优先
Coder_Boy_5 分钟前
基于SpringAI的智能AIOps项目:部署相关容器化部署管理技术图解版
人工智能·spring boot·算法·贪心算法·aiops
王哈哈^_^6 分钟前
【完整源码+数据集】道路拥塞数据集,yolo道路拥塞检测数据集 8921 张,交通拥堵识别数据集,路口拥塞识别系统实战教程
深度学习·算法·yolo·目标检测·计算机视觉·分类·毕业设计
Chen不旧7 分钟前
Java模拟死锁
java·开发语言·synchronized·reentrantlock·死锁
菩提树下的凡夫16 分钟前
如何将python的程序py文件转换为exe程序
开发语言·python
萧曵 丶18 分钟前
Java 安全的单例模式详解
java·开发语言·单例模式
leoufung23 分钟前
LeetCode 64. Minimum Path Sum 动态规划详解
算法·leetcode·动态规划
superman超哥23 分钟前
Rust 错误处理模式:Result、?运算符与 anyhow 的最佳实践
开发语言·后端·rust·运算符·anyhow·rust 错误处理
lly20240624 分钟前
Web 品质样式表
开发语言
Wang's Blog24 分钟前
Nodejs-HardCore: 模块管理与I/O操作详解
开发语言·nodejs