Featured image of post 洛谷P3371题解

洛谷P3371题解

封面来源

Pixiv elevenses-66979494

SPFA

 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
62
63
64
#include<bits/stdc++.h>
#define FOR(i,l,r) for(register int i=l;i<=r;i++)
#define Graph(u) for(register int i=head[u];i;i=e[i].next)
using namespace std;

const int N=1e4+7,M = 5e5+5;
const int inf=2147483647;
int n,m,s;
bool trap[N];
struct Edge{
    int u,v,w,next;
}e[M];
int tot,head[M];
inline void addEdge(int u,int v,int w){
e[++tot].u=u;
e[tot].v=v;
e[tot].w=w;
e[tot].next=head[u];
head[u]=tot;
}
int dis[N],vis[N];
void spfa(int s){
    queue<int> q;
    // q.push({1,k+1-trap[s]});
    // memset(dis,0x3f,sizeof(dis));
    FOR(i,1,n){
        dis[i]=inf;
    }
    dis[s]=0;
    q.push(s);
    while(!q.empty()){
        int u = q.front();
        q.pop();
        vis[u]=0;
        Graph(u){
            int v=e[i].v;
            if(dis[v]>dis[u]+e[i].w){
                dis[v]=dis[u]+e[i].w;
                if(!vis[v]){
                    q.push(v);
                    vis[v]=1;
                }
            }
        }
    }
}
int main(){
#ifdef LOCAL
freopen("1.in","r",stdin);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n>>m>>s;
    FOR(i,1,m){
        int u,v,w;
        cin>>u>>v>>w;
        addEdge(u,v,w);
    }
    spfa(s);
    FOR(i,1,n){
        cout<<dis[i]<<" ";
    }
    return 0;
}
所念皆星河
Built with Hugo
主题 StackJimmy 设计