SPFA

#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=1e6+10;
const int maxm=2*maxn;
struct Edge{
	int u,v,w;
}edge[maxm];
int head[maxn],cnt;
inline void add(int u,int v,int w){edge[++cnt].u=head[u],edge[cnt].v=v,edge[cnt].w=w,head[u]=cnt;}
int dis[maxn],vis[maxn];
queue<int>q;
int n,m;
inline void spfa(int s)
{
	memset(dis,0x7f,sizeof(dis));
	memset(vis,0,sizeof(vis));
	dis[s]=0,vis[s]=1,q.push(s);
	while(!q.empty())
	{
		int cur=q.front();q.pop(),vis[cur]=0;
		for(int i=head[cur];i;i=edge[i].u)
		{
			int v=edge[i].v;
			if(dis[v]>dis[cur]+edge[i].w)
			{
				dis[v]=dis[cur]+edge[i].w;
				if(!vis[v])vis[v]=1,q.push(v);
			}
		}
	}
	printf("Shortest Paths from point %d are: ",s);
	for(int i=1;i<=n;i++)printf("%d ",dis[i]);
	puts("");
}
int main()
{
	int u,v,w;
	scanf("%d%d",&n,&m);
	while(m--)scanf("%d%d%d",&u,&v,&w),add(u,v,w),add(v,u,w);
	for(int i=1;i<=n;i++)spfa(i);
	return 0;
}

  

posted @ 2017-12-23 10:15  baka  阅读(153)  评论(0编辑  收藏  举报