BZOJ2200 道路与航线(dijk+拓扑排序)

Description

Farmer John正在一个新的销售区域对他的牛奶销售方案进行调查。他想把牛奶送到T个城镇 (1 <= T <= 25,000),编号为1T。这些城镇之间通过R条道路 (1 <= R <= 50,000,编号为1到R) 和P条航线 (1 <= P <= 50,000,编号为1到P) 连接。每条道路i或者航线i连接城镇A_i (1 <= A_i <= T)到B_i (1 <= B_i <= T),花费为C_i。对于道路,0 <= C_i <= 10,000;然而航线的花费很神奇,花费C_i可能是负数(-10,000 <= C_i <= 10,000)。道路是双向的,可以从A_i到B_i,也可以从B_i到A_i,花费都是C_i。然而航线与之不同,只可以从A_i到B_i。事实上,由于最近恐怖主义太嚣张,为了社会和谐,出台 了一些政策保证:如果有一条航线可以从A_i到B_i,那么保证不可能通过一些道路和航线从B_i回到A_i。由于FJ的奶牛世界公认十分给力,他需要运送奶牛到每一个城镇。他想找到从发送中心城镇S(1 <= S <= T) 把奶牛送到每个城镇的最便宜的方案,或者知道这是不可能的。

Input

  • 第1行:四个空格隔开的整数: T, R, P, and S * 第2到R+1行:三个空格隔开的整数(表示一条道路):A_i, B_i 和 C_i * 第R+2到R+P+1行:三个空格隔开的整数(表示一条航线):A_i, B_i 和 C_i

Output

  • 第1到T行:从S到达城镇i的最小花费,如果不存在输出"NO PATH"。

单向边没有负权且没有单向边不会出现在环里。考虑开始只加入双向边,我们就得到了一个有若干个连通块组成的图,把每个连通块看成一个点,再加入单向边,就相当于一个有向无环图。所以我们可以按拓扑序处理最短路。在每个连通块内部进行Dijkstra。
这题中,在Dijkstra过程中,从堆中取一个点u松弛它所有出边的终点v, 如果u,v不在同一连通块中,我们要将v所在连通块入度减一,若v所在连通块入度为0,就把所在连通块加入拓扑排序中。

坑点:有可能有s达不到的点被负权边松弛,所以如果dis初始化为inf,判断输出时不能 if(dis[i] == inf)

#include<bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
const int N = 50010;
queue<int> topo;
priority_queue<pii> q;
int t,r,p,s;
struct Edge{
	int v,w,next;
}edge[N*4];
int head[N * 4],tot;
void add(int u,int v,int w){
	edge[++tot].v = v;
	edge[tot].w = w;
	edge[tot].next = head[u];
	head[u] = tot;
}
int c[N],deg[N],cnt,vis[N],dis[N];
void dfs(int s){
	c[s] = cnt;
	for(int i = head[s]; i; i = edge[i].next)
		if(!c[edge[i].v]) dfs(edge[i].v);
}
void topo_dijk(){
	memset(dis,0x7f,sizeof(dis));
	memset(vis,0,sizeof(vis));
	dis[s] = 0;
	topo.push(c[s]);
	for(int i = 1; i <= cnt; ++i)
		if(!deg[i]) topo.push(i);
	while(!topo.empty()){
		int p = topo.front(); topo.pop();
		for(int i = 1; i <= t; ++i)
			if(c[i] == p) q.push(make_pair(-dis[i],i));
		while(!q.empty()){
			int u = q.top().second; q.pop();
			if(vis[u]) continue;
			vis[u] = 1;
			for(int i = head[u]; i; i = edge[i].next){
				int v = edge[i].v;
				if(dis[v] > dis[u] + edge[i].w){
					dis[v] = dis[u] + edge[i].w;
					if(c[u] == c[v]) q.push(make_pair(-dis[v],v));
				}
				if(c[u] != c[v]) 
					if(--deg[c[v]] == 0) topo.push(c[v]);
			}
		}
	}
	
}
int main(){
	cin >> t >> r >> p >> s;
	for(int i = 1; i <= r; ++i){
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		add(a,b,c); add(b,a,c);
	}	
	for(int i = 1; i <= t; ++i){
		if(!c[i]) {
			++cnt;
			dfs(i);
		}
	}
	for(int i = 1; i <= p; ++i){
		int a,b,cc;
		scanf("%d%d%d",&a,&b,&cc);
		add(a,b,cc); 
		deg[c[b]]++;
	}
	topo_dijk();
	for(int i = 1; i <= t; ++i)
		if(dis[i] > 0x3f3f3f3f) cout << "NO PATH" <<endl;
		else cout << dis[i] << endl;
	return 0;
} 
posted @ 2019-08-24 21:31  foxc  阅读(211)  评论(0编辑  收藏  举报