道路与航线

一道类似缩点的好题,先按道路缩点 然后将缩点以后的图按照航线做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;
}
相关推荐
枫叶林FYL14 分钟前
【群体智能集群控制工程实践】第3章 一致性协同算法
算法
禹凕32 分钟前
滑动窗口算法实战指南
python·算法
DisonTangor39 分钟前
【腾讯混元雪耻归来】 Hy4 preview:770B 参数 MoE 旗舰模型,1M 上下文全面开源
人工智能·算法·开源·aigc·腾讯云·腾讯云ai代码助手
明月_清风2 小时前
从二叉树到 B+ 树:一文搞懂工程中「树」的演化之道
数据结构·算法·go
渡我白衣2 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
天下无敌笨笨熊2 小时前
C#Modbus串口开发心得
开发语言·c#
电商API_180079052472 小时前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘
zzzll11112 小时前
深度剖析:HashMap 并发死循环与 ConcurrentHashMap 两代演进全解
java·开发语言
如意猴2 小时前
【C++】001--C++入门(1)
开发语言·c++
hetao17338372 小时前
2026-09-01~09-04 hetao1733837 的刷题记录
c++·算法