spfa(前向星)

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<queue>
#define inf 99999999
using namespace std;
const int maxn=110;
int e,dis[maxn],vis[maxn],to[maxn],be[maxn],ne[maxn],w[maxn];
void add(int x,int y,int z){
	to[++e]=y;
	ne[e]=be[x];
	be[x]=e;
	w[e]=z;
}
queue<int>q;
int main(){
	int i,j,k,m,n;
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;i++){
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
		add(y,x,z);
	}
	for(i=1;i<=n;i++)dis[i]=inf;
	dis[1]=0;
	vis[1]=1;
	q.push(1);
	while(!q.empty()){
		int u=q.front();
		q.pop();
		vis[u]=0;
		for(i=be[u];i;i=ne[i]){
			int v=to[i];
			if(dis[v]>dis[u]+w[i]){
				dis[v]=dis[u]+w[i];
				 if(!vis[v]){
					q.push(v);
					vis[v]=1; 	
				}
			}
		}
	}
	for(i=1;i<=n;i++){
		printf("%d",dis[i]);
	}
	return 0;
}
/*
5 7
1 2 2
1 5 10
2 3 3
2 5 7
3 4 4
4 5 5
5 3 6

*/

posted @ 2016-09-16 17:22  Drinkwater_cnyali  阅读(149)  评论(0编辑  收藏  举报