/**
差分约束 Dijkstra 模板(数组)
这题用vector会超时,后来才知道这个叫链式前向星
差分约束感觉这个博客写的比较好:http://blog.csdn.net/xuezhongfenfei/article/details/8685313
**/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int INF=1<<27;
const int maxn=30005;
struct HeapNode//优先队列的节点
{
int d,u;
bool operator < (const HeapNode& rhs) const
{
return d>rhs.d;
}
};
struct Edge
{
int next,to,dist; //next表示从同一个点出发相邻的边
}edges[150005];
struct Dijkstra
{
int n,m,total;//点数和边数
int head[maxn]; //每个点出发的边编号(从0开始编号)
bool done[maxn]; //是否已经永久标号
int d[maxn]; //s到各个点之间的距离
int p[maxn]; //最短路中的上一条边
void init(int n)
{
this->n=n;
memset(head,-1,sizeof(head));
total=0;
}
void AddEdge(int from,int to,int dist)
{
edges[total].to=to;
edges[total].dist=dist;
edges[total].next=head[from];
head[from]=total++;
}
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=head[u];i!=-1;i=edges[i].next)
{
Edge& e=edges[i];
if(d[e.to]>d[u]+e.dist)
{
d[e.to]=d[u]+e.dist;
p[e.to]=u;
Q.push((HeapNode){d[e.to],e.to});
}
}
}
}
};
int main()
{
int n,m,i,x,y,z;
Dijkstra solver;
scanf("%d%d",&n,&m);
solver.init(n);
for(i=0;i<m;i++)
{
scanf("%d%d%d",&x,&y,&z);
solver.AddEdge(x-1,y-1,z);
}
solver.dijkstra(0);
printf("%d\n",solver.d[n-1]);
return 0;
}
差分约束系统 Dijkstra模板(2)
最新推荐文章于 2023-07-08 13:40:23 发布