dijkstra朴素版
#include<iostream>
#include<cstring>
using namespace std;
const int N=505;
int g[N][N];
int st[N];
int dist[N];
int point,line;
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[1]=0;
for(int k=1;k<=point;k++)
{
int t=-1;
for(int j=1;j<=point;j++)
{
if(!st[j]&&(t==-1||dist[j]<dist[t]))
{
t=j;
}
}
st[t]=1;
for(int j=1;j<=point;j++)
{
dist[j]=min(dist[j],dist[t]+g[t][j]);
}
}
if(dist[point]==0x3f3f3f3f) return -1;
return dist[point];
}
int main()
{
memset(g,0x3f3f3f3f,sizeof g);
cin>>point>>line;
for(int k=1;k<=line;k++)
{
int c,d,e;
cin>>c>>d>>e;
g[c][d]=min(g[c][d],e);
}
cout<<dijkstra()<<endl;
return 0;
}
堆优化
#include<bits/stdc++.h>
using namespace std;
const int N=150000;
int h[N],e[N],ne[N],w[N],idx;
int dist[N];
bool st[N];
int n,m;
typedef pair <int,int> PII;
void add(int a,int b,int c)
{
e[idx]=b;
ne[idx]=h[a];
w[idx]=c;
h[a]=idx++;
}
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[1]=0;
priority_queue<PII, vector<PII>, greater<PII> > heap;
heap.push({0,1});
while(heap.size())
{
PII j = heap.top();
heap.pop();
int d = j.first;
int ver = j.second;
if(st[ver]) continue;
st[ver]=true;
for(int k=h[ver];k!=-1;k=ne[k])
{
int j=e[k];
if(dist[j]>d+w[k])
{
dist[j]=d+w[k];
heap.push({dist[j],j});
}
}
}
if(dist[n]==0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
for(int k=1;k<=m;k++)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cout<<dijkstra()<<endl;
return 0;
}
prim
#include<bits/stdc++.h>
using namespace std;
const int N=1e3;
int n[N][N];
int dist[N];
bool st[N];
int pre[N];
int point,line;
int prim()
{
memset(dist,0x3f,sizeof dist);
int res=0;
dist[1]=0;
for(int k=1;k<=point;k++)
{
int t=-1;
for(int j=1;j<=point;j++)
{
if(!st[j]&&(t==-1||dist[j]<dist[t]))
t=j;
}
st[t]=1;
res+=dist[t];
for(int j=1;j<=point;j++)
{
if(dist[j]>n[t][j]&&!st[j])
{
dist[j]=n[t][j];
pre[j]=t;
}
}
}
if(res>=0x3f3f3f3f/2) return -1;
return res;
}
int main()
{
int a,b,c;
memset(n,0x3f,sizeof n);
cin>>point>>line;
for(int k=1;k<=line;k++)
{
cin>>a>>b>>c;
n[b][a]=n[a][b]=min(n[a][b],c);
}
int ans=prim();
if(ans==-1) cout<<"impossible"<<endl;
else cout<<ans;
return 0;
}