SPFA算法
阿新 • • 發佈:2017-12-12
main ring scan 最短路 name stream clu true ron
n個點,m條邊,源點s,求單源最短路徑
#include <stdio.h> #include <queue> using namespace std; struct node { int x; int next; int val; }a[40001]; int n,m; int dis[2001],st[2001],vis[2001]; void spfa(int x) { queue<int> q; int i; q.push(x); vis[x]=1; dis[x]=0; while(!q.empty()) { int f=q.front(); q.pop(); vis[f]=0; i=st[f]; while(i) { int b=a[i].x; int eg=a[i].val; if(dis[b] > dis[f] + eg) { dis[b]=dis[f] + eg; if(b == x) {if(dis[b] < 0) { printf("EL PSY CONGROO\n"); return; } } if(!vis[b]) { q.push(b); vis[b]=1; } } i=a[i].next; } } printf("ttt\n"); } int main() { int u,v,w,i; scanf("%d %d",&n,&m); for(i=1; i<=2001; i++) { vis[i]=0; dis[i]=10000000; st[i]=0; } for(i=1; i<=m; i++) { scanf("%d %d %d",&u,&v,&w); a[i].x=v; a[i].val=w; a[i].next=st[u]; st[u]=i; } scanf("%d",&u); spfa(u); return 0; }
上面一個比下面一個快
#include<iostream> #include<queue> #include<string.h> #include<stdio.h> using namespace std; const int maxn = 40001; struct Edge { int to; int next; int w; }edge[maxn]; int p[maxn],dis[maxn],in[maxn]; bool vis[maxn]; int n,m; void spfa(int s) { int i,t,temp; queue<int> q; memset(vis,0,sizeof(vis)); memset(dis,0x3f,sizeof(dis)); memset(in,0,sizeof(in)); q.push(s); vis[s]=true; dis[s]=0; while(!q.empty()) { t=q.front(); q.pop(); vis[t]=false; for(i=p[t];i;i=edge[i].next) { temp=edge[i].to; if(dis[temp]>dis[t]+edge[i].w) { dis[temp]=dis[t]+edge[i].w; if(!vis[temp]) { q.push(temp); vis[temp]=true; if(++in[temp]>n) { printf("EL PSY CONGROO"); return; } } } } } printf("ttt"); return; } int main(){ int i,s,u,v,w,cnt=0; //cin>>n>>m; scanf("%d %d",&n,&m); for(i=1;i<=m;i++) { //cin>>u>>v>>w; scanf("%d %d %d",&u,&v,&w); edge[++cnt].to=v; edge[cnt].next=p[u]; edge[cnt].w=w; p[u]=cnt; } //cin>>s; scanf("%d",&s); spfa(s); return 0; }
SPFA算法