struct Edge{ int from,to,dist; }; struct HeapNode{ int d,u; bool operator <(const HeapNode &rhs)const{ return d>rhs.d; } }; struct Dijkstra{ int n,m;//点和边数 vector<Edge>edges;//边列表 vector<int>G[MAXN];//每个节点出发的边编号(从0开始编号) bool done[MAXN];//是否永久标记 int d[MAXN];//s到各个点的距离 int p[MAXN];//最短路中的上一条边 void init(int n) { this->n=n; for(int i=0;i<n;i++)G[i].clear();//清空邻接表 edges.clear();//清空边表 } void AddEdge(int from,int to,int dist) { //如果是无向图,每条无向边需调用2次AddEdge edges.push_back((Edge){from,to,dist}); m=edges.size(); G[from].push_back(m-1); } void dijkstra(int s) {//求s到所有点的距离 priority_queue<HeapNode> Q; for(int i=0;i<n;i++)d[i]=INF; d[s]=0; memset(done,0,sizeof(done)); Q.push((HeapNode){0,s}); while(!Q.empty()) { HeapNode x=Q.top();Q.pop(); int u=x.u; if(done[u])continue; done[u]=true; for(int i=0;i<G[u].size();i++) { Edge& e=edges[G[u][i]]; if(d[e.to]>d[u]+e.dist) { d[e.to]=d[u]+e.dist; p[e.to]=G[u][i]; Q.push((HeapNode){d[e.to],e.to}); } } } } };