首页 > 代码库 > 堆优化 dijkstra +路径

堆优化 dijkstra +路径

#include <iostream>#include <cstdio>#include <algorithm>#include <queue>#include <bits/stdc++.h>using namespace std;const int N = 10010;const int oo = 99999999;int dis[N], pre[N];bool vis[N];int n, m, S;struct Node{	int u, v, w;	Node(int u, int v, int w):u(u), v(v), w(w) {}};struct Headnode{	int dis_this, u;	bool operator < (const Headnode& now) const	{		return dis_this > now.dis_this;	}};vector <int> G[N];vector <Node> EE;inline int read(){	int x = 0; char c = getchar();	while(c < ‘0‘ || c > ‘9‘)c = getchar();	while(c >= ‘0‘ && c <= ‘9‘)x = x * 10 + c - ‘0‘, c = getchar();	return x;}inline void dijkstra(int start){	priority_queue <Headnode> Q;	for(int i = 1; i <= n; i ++)		dis[i] = oo;	dis[start] = 0;	memset(vis, 0, sizeof(vis));	Headnode HHH;	HHH.dis_this = 0;	HHH.u = start;	Q.push(HHH);	while(!Q.empty())	{		Headnode topp = Q.top();		Q.pop();		int u = topp.u;		if(vis[u])			continue;		for(int i = 0; i < G[u].size(); i ++)		{			Node e = EE[G[u][i]];			if(dis[e.v] > dis[u] + e.w)			{				dis[e.v] = dis[u] + e.w;				pre[e.v] = G[u][i];				Q.push((Headnode) {dis[e.v], e.v});			}		}	}}inline void add(int u,int v,int w){	EE.push_back(Node(u, v, w));	G[u].push_back(EE.size() - 1);}int main(){	n = read();	m = read();	S = 1;		for(int i = 1; i <= m; i ++)	{		int u = read();		int v = read();		int w = read();		add(u, v, w);	}	dijkstra(S);	while(1)	{		int endd = read();		printf("%d",dis[endd]);	}	return 0;}/*5 71 2 41 3 61 5 502 3 53 5 73 4 84 5 9*/

  

堆优化 dijkstra +路径