P3371 【模板】单源最短路径(弱化版)
无优化版dijkstra
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n,m,s,u,v,w,res[10005];
struct node{
ll v,w;
};
vector<node> mp[10001];
bool vis[10001];
int main(){
ios::sync_with_stdio(0);
cin>>n>>m>>s;
for(int i=1;i<=n;i++){
res[i]=2147483647;
}
for(int i=1;i<=m;i++){
cin>>u>>v>>w;
mp[u].push_back({v,w});
}
res[s]=0;
while(!vis[s]){
vis[s]=1;
ll t=2147483647,k=mp[s].size();
for(int i=0;i<k;i++){
res[mp[s][i].v]=min(res[mp[s][i].v],res[s]+mp[s][i].w);
}
for(int i=1;i<=n;i++){
if(!vis[i]&&res[i]<t){
t=res[i];
s=i;
}
}
}
for(int i=1;i<=n;i++){
cout<<res[i]<<' ';
}
return 0;
}
P4779 【模板】单源最短路径(标准版)
链式前向星+堆优化dijkstra
#include<bits/stdc++.h>
using namespace std;
#define inf 0x7fffffff
#define int long long
int head[500005],cnt,n,v,u,w,s,m,vis[500005],res[500005];
struct node{
int from,to,w,next;
friend bool operator <(const node&x,const node&y){
return x.w>y.w;
}
}e[500005];
priority_queue<node> q;
void add_edge(int from,int to,int w){
e[++cnt].to=to;
e[cnt].w=w;
e[cnt].from=from;
e[cnt].next=head[from];
head[from]=cnt;
}
signed main(){
ios::sync_with_stdio(0);
cin>>n>>m>>s;
for(int i=1;i<=m;i++){
cin>>u>>v>>w;
add_edge(u,v,w);
}
for(int i=1;i<=n;i++)res[i]=inf;
res[s]=0;
q.push({s,0,0,0});
while(!q.empty()){
node t=q.top();
q.pop();
if(!vis[t.from]){
vis[t.from]=1;
for(int i=head[t.from];i;i=e[i].next){
if(res[e[i].to]>res[t.from]+e[i].w){
res[e[i].to]=res[t.from]+e[i].w;
q.push({e[i].to,0,res[e[i].to],0});
}
}
}
}
for(int i=1;i<=n;i++){
cout<<res[i]<<' ';
}
return 0;
}