#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
const int inf = 1<<30;
const int L = 200000;
struct Edges
{
int x,y,w,next;
} e[L<<2];
int head[L];
int dis[L];
int vis[L];
int cnt[L];
void AddEdge(int x,int y,int w,int k)
{
e[k].x = x,e[k].y = y,e[k].w = w,e[k].next = head[x],head[x] = k;
}
int relax(int u,int v,int c)
{
if(dis[v]>dis[u]+c)
{
dis[v] = dis[u]+c;
return 1;
}
return 0;
}
int SPFA(int src)
{
int i;
memset(cnt,0,sizeof(cnt));
dis[src] = 0;
queue<int> Q;
Q.push(src);
vis[src] = 1;
cnt[src]++;
while(!Q.empty())
{
int u,v;
u = Q.front();
Q.pop();
vis[u] = 0;
for(i = head[u]; i!=-1; i=e[i].next)
{
v = e[i].y;
if(relax(u,v,e[i].w)==1 && !vis[v])
{
Q.push(v);
vis[v] = 1;
}
}
}
}
int main()
{
int t,n,m;
int i,j;
scanf("%d%d",&n,&m);
memset(e,-1,sizeof(e));
for(i = 1; i<=n; i++)
{
dis[i] = inf;
vis[i] = 0;
head[i] = -1;
}
for(i = 0; i<m; i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
AddEdge(x,y,w,i);
}
SPFA(1);
for(i = 2; i<=n; i++)
printf("%d\n",dis[i]);
return 0;
}
#include<iostream>
#include<queue>
#include<memory.h>
using namespace std;
const int inf=1<<30;
const int N=200005;
struct Edge
{
int u,v,w,next;
};
int head[N];
int dis[N];
int vis[N];
Edge e[N];
void addEdge(int from,int to,int we,int i)
{
e[i].u=from;
e[i].v=to;
e[i].w=we;
e[i].next=head[from];
head[from]=i;
}
bool releax(int u,int v,int w)
{
if(dis[u]+w<dis[v])
{
dis[v]=dis[u]+w;
return true;
}
return false;
}
void spfa(int x)
{
queue<int> q;
q.push(x);
vis[x]=1;
dis[x]=0;
while(!q.empty())
{
int u,v,i;
u=q.front();
q.pop();
vis[u]=0;
for(i=head[u];i!=-1;i=e[i].next)
{
v=e[i].v;
if(!vis[v]&&releax(u,v,e[i].w))
{
q.push(v);
vis[v]=1;
}
}
}
}
int main()
{
//cout<<inf<<' '<<N<<endl;
int n,m,i,u,v,w;
//memset(head,-1,sizeof(head));
//memset(dis,inf,sizeof(dis));
//memset(vis,0,sizeof(vis));
//memset(e,-1,sizeof(e));
cin>>n>>m;
for(i=1;i<=n;i++)
{
head[i]=-1;
dis[i]=inf;
vis[i]=0;
}
for(i=1;i<=m;i++)
{
cin>>u>>v>>w;
addEdge(u,v,w,i);
}
/*for(i=1;i<=m;i++)
{
cout<<e[i].u<<' '<<e[i].v<<' '<<e[i].next<<endl;
}
for(i=1;i<=3;i++)
cout<<head[i]<<' ';*/
spfa(1);
for(i=2;i<=n;i++)
{
cout<<dis[i]<<endl;
}
return 0;
}
转载于:https://www.cnblogs.com/u013533289/p/4477268.html