复杂度:O(m+n)logn
const int maxn=2505;
const int inf=0x3f3f3f3f;
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 &r)const
{
return d>r.d;
}
};
struct Dijkstra
{
int n;
vector <Edge> edges;//保存所有边
vector <int> G[maxn];//只保存边的编号
bool done[maxn];//访问标记
int d[maxn];//到每个点的距离
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)
{
edges.push_back(Edge(from,to,dist));
int m=edges.size();
G[from].push_back(m-1);
}
void dijkstra (int s)
{
priority_queue<heapnode> q;
memset(d,inf,sizeof(d));
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]=e.from;
q.push(heapnode{d[e.to],e.to});
}
}
}
}
void print(int u,int s)//打印路径 起点 终点
{
if(s==u)
{
printf("%d",u);
return;
}
print(u,p[s]);
printf(" %d",s);
}
};