#include<iostream>
#include<algorithm>
#include<queue>
#include<utility>
#include<vector>
#include<cstring>
using namespace std;
typedef pair<int,int> PII;
const int N=5000;
int h[N],e[N],ne[N],w[N],idx;
bool st[N];
priority_queue<PII,vector<PII>,greater<PII> > heap;
int n,s;
int dist[N];
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void Dijkstar()
{
memset(dist,0x3f,sizeof(dist));
dist[s]=0;
heap.push({0,s});
while(!heap.empty())
{
PII t=heap.top();
heap.pop();
int i=t.second,dect=t.first;
if(st[i])
continue;
for(int j=h[i];j!=-1;j=ne[j])
{
int k=e[j],weight=w[j];
if(dist[k]>dect+weight)
{
dist[k]=dect+weight;
heap.push({dist[k],k});
}
}
st[i]=true;
}
}
int main()
{
memset(h,-1,sizeof(h));
cin>>n>>s;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int a;
cin>>a;
if(a!=0)
{
add(i,j,a);
}
}
}
Dijkstar();
for(int i=0;i<n;i++)
{
if(i!=s)
{
if(dist[i]!=0x3f3f3f3f)
cout<<dist[i]<<" ";
else
cout<<-1<<" ";
}
}
}
Dijkstra堆优化邻接表
最新推荐文章于 2022-11-18 22:42:12 发布