稀疏图:点多边少
稠密图:点少边多
#include<bits/stdc++.h>
using namespace std;
using ll =long long;
const ll N=3E5+9,inf=2e18;
ll d[N];
int n,m;
struct Node
{
ll x,w;
bool operator < (const Node &y) const
{
return w==y.w ? x< y.x : w>y.w;
}
};
vector<Node>g[N];//存贮图
void dijkstra(ll st)//参数表示源点
{
for(int i=1;i<=n;i++)d[i]=inf;
bitset<N>vis;
priority_queue<Node> pq;
pq.push({st,d[st]=0});
while(pq.size())
{
auto[x,w]=pq.top();pq.pop();
if(vis[x])continue;
vis[x]=true;
for(const auto & [y,dw]:g[x])
{
if(d[x]+dw<d[y])
{
d[y]=d[x]+dw;
pq.push({y,d[y]});
}
}
}
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>m;
while(m--)
{
ll u,v,w;cin>>u>>v>>w;
g[u].push_back({v,w});
}
dijkstra(1);
for(int i=1;i<=n;i++)
{
cout<<(d[i]>=inf ? -1 : d[i])<<" ";
}
return 0;
}