spfa模板

来源:互联网 发布:武神赵子龙辅助软件 编辑:程序博客网 时间:2024/05/17 23:40
#include<cstdio>#include<iostream>#include<cstring>#include<set>#include<map>#include<queue>#include<vector>#include<ctime>#include<cstdlib>#include<algorithm>using namespace std;queue<int> q;const int inf=2147483647;int dis[1100000],vis[1100000],head[1100000],nex[2100000],to[2100000],cos[1100000],n,m,s,tot;void add(int x,int y,int z){ //邻接链表     nex[++tot]=head[x];    to[tot]=y;    cos[tot]=z;    head[x]=tot;}void spfa(){ //spfa O(E*K)求单源最短路     vis[s]=1;    for(int i=1;i<=n;i++) dis[i]=inf;    q.push(s);    dis[s]=0;    while(!q.empty()){        int x=q.front();q.pop();vis[x]=0;        for(int i=head[x];i;i=nex[i]){            int tmp=to[i];            if(dis[tmp]>dis[x]+cos[i]){                dis[tmp]=dis[x]+cos[i];                if(!vis[tmp]) vis[tmp]=1,q.push(tmp);            }        }    }} int main(){    scanf("%d%d%d",&n,&m,&s);    for(int i=1,x,y,z;i<=m;i++) scanf("%d%d%d",&x,&y,&z),add(x,y,z);     spfa();    for(int i=1;i<=n;i++) printf("%d ",dis[i]); }
原创粉丝点击