洛谷日刷 | Eternal_zttz

洛谷日刷

P3371 【模板】单源最短路径(弱化版)

洛谷传送门

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <cstdio>
#include <queue>
using namespace std;
#define INF 2147483647
typedef long long ll;
typedef struct Edge{
int u,v,w,nxt;
}edge;
edge e[500010];
int head[100010];
int cnt = 0;
void addedge(int u,int v,int w){
e[++cnt] = {u,v,w,head[u]};
head[u] = cnt;
}
int n,m,s;
ll dis[100010];
struct node{
ll u,d;
bool operator <(const node&rhs)const{
return d>rhs.d;
}
};
void dijkstra(){
for (int i =1;i<=n;i++)
dis[i] = INF;
dis[s] = 0;
priority_queue<node> q;
q.push((node){s,0});
while(!q.empty()){
node flag = q.top();
q.pop();
ll u = flag.u,d = flag.d;
if(d!=dis[u]) continue;
for (int i = head[u];i;i=e[i].nxt){
int v = e[i].v,w = e[i].w;
if(dis[v]>dis[u]+w){
dis[v] = dis[u]+w;
q.push((node){v,dis[v]});
}
}
}
}
int main(){
scanf("%d %d %d",&n,&m,&s);
for (int i = 1;i<=m;i++){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
addedge(a,b,c);
}
dijkstra();
for (int i = 1;i<=n;i++){
printf("%lld ",dis[i]);
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#define M 1000005
#define N 100005
#define INF 2147483647
using namespace std;
struct node {
int u,v,w,next;
};
int head[N],len[N];
bool vis[N];
int n,m,cnt,s = 1;
void add(node edge[],int u,int v,int w){
edge[cnt]={u,v,w,head[u]};
head[u] = cnt++;
}
void SPFA(queue<int>q,node edge[]){
q.push(s);
vis[s] = true;
for (int i=1;i<=n;i++)
len[i] = INF;
len[s] = 0;
while(!q.empty()){
int u = q.front();
q.pop();
vis[u] = false;
for (int i = head[u];i>0;i=edge[i].next){
int v = edge[i].v;
int w = edge[i].w;
if(len[v]> len[u]+w){
len[v] =len[u]+w;
if(!vis[v]){
vis[v] =true;
q.push(v);
}
}
}
}
}
int main(){
while(~scanf("%d %d %d",&n,&m,&s)){
node edge[m+1];
cnt = 1;
memset(head,0, sizeof(head));
memset(len,0,sizeof(len));
memset(vis,false,sizeof(vis));
queue<int>q;
for (int i =1;i<=m;i++){
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
add(edge,u,v,w);
}
SPFA(q, edge);
for (int i =1;i<=n;i++){
printf("%d ",len[i]);
}
printf("\n");
}
}
-------------The End-------------