Dijkstra + heap optimization + adjacency list

When the shortest path problem of about 10,000 data is involved in the PAT test questions, the Dijkstra algorithm can be solved in a very short time by optimizing the minimum heap. If Dijkstra's algorithm and adjacency table representation are not used, it is likely to time out. The following shows the optimization of Dijkstra's algorithm with the priority queue of stl in c++. With it and DFS, the shortest path problem encountered in PAT can be basically solved (most of the shortest path vertices do not exceed 1000 , But sometimes when there is 10000, the following template can also be used calmly.)

struct Node{
	int v, dis;//v代表顶点,dis代表边权 
};
vector<Node> Adj[maxn];//图的邻接表示法 
struct HeapNode{
	int v,d;//v代表图中点,d代表源点到v的当前的最短距离 
	HeapNode(){}
	HeapNode(int V, int D){v=V; d=D;}
	friend bool operator < (HeapNode v1, HeapNode v2){//为使用优先级队列做准备 
		return v1.d > v2.d;
	}
};
bool vis[maxn] = {false};
int d[maxn];//源点到该点的最短距离 
void Dijkstra(int s)
{
	priority_queue<HeapNode> q;//优先级队列 
	fill(d,d+maxn,inf);
	d[s] = 0;
	q.push(HeapNode(s,0));
	while(!q.empty()){
		int u;
		u = q.top().v;q.pop();
		for(int j=0; j<Adj[u].size(); j++){
			int v = Adj[u][j].v;
			if(vis[v]==false){
				if(d[u]+Adj[u][j].dis<d[v]){
					d[v] = d[u]+Adj[u][j].dis;
					q.push(HeapNode(v,d[v]));
					pre[v].clear();
					pre[v].push_back(u);
				}
				else if(d[u]+Adj[u][j].dis==d[v]){
					pre[v].push_back(u);
				}
			}
		}
	}
}

 

 

 

Guess you like

Origin blog.csdn.net/yiwaite/article/details/106197181