图论里非常常用的dijkstra,自己加了个路径查找,做个模板吧:
int maxn = 100005; struct Edge { int from,to,dist; Edge(int u, int v, int d):from(u),to(v),dist(d) {} }; 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]; bool done[maxn]; int d[maxn]; int p[maxn]; //最短路中的上一条弧 vector<int> path; void init(int n) { this->n = n; for (int i = 0; i < n; i++) G[i].clear(); edges.clear(); path.clear(); } void addEdge(int from, int to, int dist) { 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 }); } } } } void findpath(int x,int end) { path.clear(); path.push_back(x); findd(x,end); } void findd(int x,int end) { if(x==end) return; else { path.push_back(this->edges[this->p[x]].from); findd(this->edges[this->p[x]].from,end); } } };