首页 > 代码库 > SPFA模板

SPFA模板

更改了一下不应-羁绊的模板,更加实用了。

#include <iostream>#include <fstream>#include <cstring>#include <cstdio>#include <algorithm>#include <iomanip>#include <vector>#include <cstdlib>#include <ctime>#include <string>#include <queue>#include <map>#include <cmath>using namespace std;#define maxn 10000#define inf 0x3f3f3f3fstruct Edge {    int w;    int v;};int spfa(vector<vector<Edge> >& vadj,int n,int s,int t){    int dist[maxn];    for(int i=0;i<n;i++)        dist[i] = inf;    dist[s] = 0;    bool vis[maxn];    memset(vis,false,sizeof(vis));    vis[s] = true;    queue<int> Q;    Q.push(s);    while(Q.size())    {        int u = Q.front();        Q.pop();        vis[u] = false;        for(int i=0;i<vadj[u].size();i++)        {            Edge next = vadj[u][i];            if(dist[next.v]>dist[u]+next.w)            {                dist[next.v] = dist[u]+next.w;                if(!vis[next.v])                {                    Q.push(next.v);                    vis[next.v] = true;                }            }        }    }    return dist[t];}int main(){    //freopen("input.txt","r",stdin);    int n,m;    cin>>n>>m;    int s,t;    cin>>s>>t;    --s;    --t;    vector<vector<Edge> > vadj(n);    for(int i=0;i<m;i++)    {        int u,v,d;        scanf("%d%d%d",&u,&v,&d);        --u;        --v;        Edge edge1,edge2;        edge1.v = v;        edge1.w = d;        edge2.v = u;        edge2.w = d;        vadj[u].push_back(edge1);        vadj[v].push_back(edge2);    }    cout<<spfa(vadj,n,s,t)<<endl;    return 0;}

 

SPFA模板