2019ICPC银川站 H. Delivery Route HYSBZ - 2200 道路和航线 dijkstra + 拓扑排序

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
using namespace std;
#define lowbit(x) x&(-x)
typedef long long ll;
typedef pair P;
const int N = 2.5e4 + 10;
const int M = 1.5e5 + 10;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
int tot = 0;
int dist[N], bel[N];
int head[N], ver[M], edge[M], Next[M], deg[N];
vector  block[N];
void addedge(int x, int y, int z)
{
	ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
}
int cnt = 0;
void dfs(int s)
{
	block[cnt].push_back(s);
	bel[s] = cnt;
	for (int i = head[s]; i; i = Next[i])
	{	
		if (!bel[ver[i]])
		{
			dfs(ver[i]);
		}
	}
}
queue q; 
priority_queue, greater

> que; int main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); memset(dist, 0x7f, sizeof(dist)); int t, r, p, s; cin >> t >> r >> p >> s; while (r--) { int x, y, z; cin >> x >> y >> z; addedge(x, y, z); addedge(y, x, z); } for (int i = 1; i <= t; i++) { if (!bel[i]) { cnt++; dfs(i); } } while (p--) { int x, y, z; cin >> x >> y >> z; addedge(x, y, z); deg[bel[y]]++; } dist[s] = 0; for (int i = 1; i <= cnt; i++) { if (deg[i] == 0) q.push(i); } while (!q.empty()) { int t = q.front(); q.pop(); for (int i = 0; i < block[t].size(); i++) que.push(P(dist[block[t][i]], block[t][i])); while (!que.empty()) { P p = que.top(); int u = p.second; que.pop(); if (dist[u] < p.first) continue; for (int i = head[u]; i; i = Next[i]) { int v = ver[i]; if (dist[v] > dist[u] + edge[i]) { dist[v] = dist[u] + edge[i]; if (bel[u] == bel[v]) { que.push(P(dist[v], v)); } } if(bel[v] != bel[u]) { deg[bel[v]]--; if (deg[bel[v]] == 0) { q.push(bel[v]); } } } } } for (int i = 1; i <= t; i++) { if (dist[i] > inf) { cout << "NO PATH\n"; } else { cout << dist[i] << "\n"; } } return 0; }

 

你可能感兴趣的:(dijkstra)