Dijkstra(迪杰斯特拉)
作者:互联网
朴素Dijkstra
时间复杂度O(n^2)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define fi first
#define se second
#define pb push_back
#define pll pair<ll,ll>
const ll mod=1e9+7;
const ll N=3e3+9;
bool book[N];
ll a[N][N],b[N];
ll n,m,s,t;
void f1(ll s)
{
for(ll i=1;i<=n;i++)
b[i]=a[s][i];
for(ll i=1;i<=n;i++)
{
ll t=-1;
for(ll j=1;j<=n;j++)
if(!book[j]&&(t==-1||b[t]>b[j]))
t=j;
book[t]=true;
for(ll j=1;j<=n;j++)
b[j]=min(b[j],b[t]+a[t][j]);
}
}
void f0(ll T)
{
cin>>n>>m>>s>>t;
for(ll i=1;i<=n;i++)
for(ll j=1;j<=n;j++)
if(i==j)
a[i][j]=0;
else
a[i][j]=1e9;
while(m--)
{
ll x,y,z;
cin>>x>>y>>z;
a[x][y]=a[y][x]=min(a[x][y],z);
}
f1(s);
cout<<b[t]<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
ll T=1;
// cin>>T;
for(ll i=1;i<=T;i++)
f0(i);
return 0;
}
堆优化Dijkstra
时间复杂度O(mlogn)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define fi first
#define se second
#define pb push_back
#define pll pair<ll,ll>
const ll mod=1e9+7;
const ll N=7e3*2+9;
struct pp
{
ll x,y,z;
}p[N];
bool book[N];
ll a[N],b[N];
ll n,m,s,t,k;
void dijkstra(ll s)
{
priority_queue<pll,vector<pll>,greater<pll>>q;
for(ll i=1;i<=n;i++)
{
b[i]=1e18;
book[i]=false;
}
b[s]=0;
q.push({0,s});
while(q.size())
{
ll x=q.top().se;
q.pop();
if(book[x])
continue;
book[x]=true;
for(ll i=a[x];i!=-1;i=p[i].x)
{
ll y=p[i].y;
if(b[y]>b[x]+p[i].z)
{
b[y]=b[x]+p[i].z;
q.push({b[y],y});
}
}
}
}
void add(ll x,ll y,ll z)
{
p[k].x=a[x];
p[k].y=y;
p[k].z=z;
a[x]=k++;
}
void f0(ll T)
{
k=0;
cin>>n>>m>>s>>t;
memset(a,-1,sizeof a);
memset(p,0,sizeof p);
while(m--)
{
ll x,y,z;
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
}
dijkstra(s);
cout<<b[t]<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
ll T=1;
// cin>>T;
for(ll i=1;i<=T;i++)
f0(i);
return 0;
}
标签:const,ll,迪杰,add,long,Dijkstra,斯特拉,void,define 来源: https://www.cnblogs.com/2021sgy/p/16564673.html