您的位置:首页 > 其它

hdu 2544 最短路裸题 SPFA

2016-11-17 23:49 316 查看
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;

#define N 100010
#define INF 0x3f3f3f3f

int n,m,q;
struct Edge{
int next,to,value;
}edge
;
int head
,tot;
bool exist
;
int dis
;
queue<int> Q;

inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}

void Addedge(int u,int v,int w)
{
tot++;edge[tot].next=head[u];edge[tot].to=v;edge[tot].value=w;head[u]=tot;
tot++;edge[tot].next=head[v];edge[tot].to=u;edge[tot].value=w;head[v]=tot;
}

void SPFA()
{
memset(dis,INF,sizeof(dis));
dis[1]=0;exist[1]=1;
Q.push(1);
while(!Q.empty())
{
int now=Q.front();Q.pop();
exist[now]=false;
for(int i=head[now];i;i=edge[i].next)
{
int v=edge[i].to;
if(dis[v]>dis[now]+edge[i].value)
{
dis[v]=dis[now]+edge[i].value;
if(!exist[v])
{
exist[v]=true;
Q.push(v);
}
}
}
}
}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0)
break;
tot=0;
memset(head,0,sizeof(head));
for(int i=1;i<=m;i++)
{
int x=read(),y=read(),z=read();
Addedge(x,y,z);
}
SPFA();
cout<<dis
<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: