P3371题目链接
P4779题目链接
解题思路:
链式前向星存图+dijkstra求单源最短路+堆优化
AC代码
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cstdlib>
#include<string>
using namespace std;
const int MAXN=1000005;
const int MAXM=500005;
const long long inf=2147483647;
struct Edge
{
int to, w, next;
};
Edge edges[MAXN];
int head[MAXM],cnt; //cnt为当前边的编号
void add(int from,int to,int w)
{
edges[++cnt].w = w; //新增一条编号为cnt+1的边,边权为w
edges[cnt].to = to; //该边的终点为to
edges[cnt].next = head[from]; //把下一条边,设置为当前起点的第一条边
head[from] = cnt; //该边成为当前起点新的第一条边
}
typedef pair<int, int> Pair;
priority_queue<Pair, vector<Pair>, greater<Pair> > Q;
long long dist[MAXN];
int vis[MAXN];
void Dij(int s)
{
dist[s] = 0;
Q.push(make_pair(0, s));
while (!Q.empty())
{
int p = Q.top().second;
Q.pop();
if (vis[p])
continue;
vis[p] = 1;
for (int e = head[p]; e != 0; e = edges[e].next)
{
int to = edges[e].to;
dist[to] = min(dist[to], dist[p] + edges[e].w);
if (!vis[to])
Q.push(make_pair(dist[to], to));
}
}
}
int main()
{
int n,m,s,u,v,w;
scanf("%d %d %d",&n,&m,&s);
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&u,&v,&w);
add(u,v,w);
}
for(int i=1;i<=n;i++)
{
dist[i]=inf;
}
dist[s]=0;
Dij(s);
for(int i=1;i<=n;i++)
{
printf("%lld ",dist[i]);
}
printf("\n");
return 0;
}