考点: 图论-最短路-Dijkstra
解题:
c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3fLL;
const int num = 3e5+2;
struct edge
{
int from,to;
long long w;
edge(int a,int b,long long c)
{
from = a;
to = b;
w = c;
}
};
vector<edge> e[num];
struct s_node
{
int id;
long long n_dis;
s_node(int b,long long c)
{
id = b;
n_dis = c;
}
bool operator < (const s_node a) const
{
return n_dis > a.n_dis;
}
};
int n,m;
long long dis[num];
void dijstra()
{
int s = 1;
bool done[num];
for(int i = 1;i <= n;i++)
{
dis[i] = inf;
done[i] = false;
}
dis[s] = 0;
priority_queue <s_node> Q;
Q.push(s_node(s,dis[s]));
while(!Q.empty())
{
s_node u = Q.top();
Q.pop();
if(done[u.id]) continue;
done[u.id] = true;
for(int i = 0;i < e[u.id].size();i++)
{
edge y = e[u.id][i];
if(done[y.to]) continue;
if(dis[y.to] > y.w +u.n_dis)
{
dis[y.to] = y.w + u.n_dis;
Q.push(s_node(y.to,dis[y.to]));
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i++) e[i].clear();
while(m--)
{
int u,v,w;
cin >> u >> v >> w;
e[u].push_back(edge(u,v,w));
}
dijstra();
for(int i = 1;i <= n;i++)
{
if(dis[i] >= inf) cout << "-1" << " ";
else cout << dis[i] << " ";
}
return 0;
}
python
import heapq
import sys
n,m=map(int,input().split())
distance=[[] for i in range(n+1)]
for i in range(m):
u,v,w=map(int,input().split())
distance[u].append((v,w))
dp=[sys.maxsize]*(n+1)
q=[]
heapq.heappush(q,(0,1))
dp[1]=0
def dijkstra():
visit=[0 for i in range(n+1)]
while q:
v=heapq.heappop(q)[1]
if visit[v]==1:
continue
visit[v]=1
for a,b in distance[v]:
if visit[a]==1:
continue
dp[a]=min(dp[a],dp[v]+b)
heapq.heappush(q,(dp[a],a))
dijkstra()
print(0,end=" ")
for i in range(2,n+1):
if dp[i]==sys.maxsize:
print(-1,end=" ")
else:
print(dp[i],end=" ")
看了一下别的大佬的解题思路,很厉害的
# 请在此输入您的代码
import math
import heapq
def djs(s):
done = [0 for _ in range(n + 1)] # bool矩阵
hp = []
dis[s] = 0
heapq.heappush(hp, (0, s))
while hp:
t = heapq.heappop(hp)[1] # 取出该节点
if done[t]:
continue
done[t] = 1
for i in range(len(g[t])): # 找t的邻居节点和距离
v, w = g[t][i]
if done[v]:
continue
if dis[v] > dis[t] + w:
dis[v] = dis[t] + w
heapq.heappush(hp, (dis[v], v))
n, m = map(int, input().split())
g = [[] for _ in range(n + 1)] # 用邻接表来储存图
dis = [math.inf] * (n + 1)
for i in range(m):
u, v, w = map(int, input().split())
g[u].append((v, w)) # 用邻接表来储存图
djs(1)
for i in range(1, n+1):
if dis[i] >= math.inf:
print(-1, end=' ')
else:
print(dis[i], end=' ')