输入样例:
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
输出:
0 2 4 3
#include<iostream>
using namespace std;
int head[100000],cnt;
long long ans[1000000];
bool vis[1000000];
int m,n,s;
struct edge
{
int to;
int nextt;
int wei;
}edge[1000000];
void addedge(int x,int y,int z)
{
edge[++cnt].to=y;
edge[cnt].wei=z;
edge[cnt].nextt=head[x];
head[x]=cnt;
}
int main()
{
cin>>n>>m>>s;
for(int i=1;i<=m;i++)
{
ans[i]=2147483647;//2的31次方-1;
}
ans[s]=0;
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
addedge(a,b,c);
}
int pos=s;
while(vis[pos]==0)
{
long long minn=2147483647;
vis[pos]=1;
for(int i=head[pos];i!=0;i=edge[i].nextt)
{
if(!vis[edge[i].to]&&ans[edge[i].to]>ans[pos]+edge[i].wei)
{
ans[edge[i].to]=ans[pos]+edge[i].wei;
}
}
for(int i=1;i<=n;i++)
{
if(ans[i]<minn&&vis[i]==0)
{
minn=ans[i];
pos=i;
}
}
}
for(int i=1;i<=n;i++)
{
cout<<ans[i]<<' ';
}
}