dijkstra
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef pair<int,int>PII;
const int N=2600,M=6200*2;
int T,C,S,E;
int h[N],e[M],ne[M],w[M],idx;
int dist[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
dist[S]=0;
priority_queue<PII,vector<PII>,greater<PII>>q;
q.push({0,S});
while(q.size())
{
auto t=q.top();
q.pop();
int ver=t.second,distance=t.first;
if(st[ver])continue;
st[ver]=true;
for(int i=h[ver];~i;i=ne[i])
{
int j=e[i];
if(dist[j]>distance+w[i])
{
dist[j]=distance+w[i];
q.push({dist[j],j});
}
}
}
return dist[E];
}
int main()
{
cin>>T>>C>>S>>E;
memset(h,-1,sizeof h);
while(C--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c),add(b,a,c);
}
cout<<dijkstra()<<endl;
return 0;
}
spfa
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int t,c,s,de;
const int N=2510,M=6300*2;
int h[N],e[M],ne[M],w[M],idx;
int dist[N],q[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void spfa()
{
memset(dist,0x3f,sizeof dist);
dist[s]=0;
int hh=0,tt=1;
q[0]=s;st[s]=true;
while(hh!=tt)//优先队列判断不相等为空
{
int t=q[hh++];
if(hh==N)hh=0;
st[t]=false;
for(int i=h[t];~i;i=ne[i])//t所接的边
{
int j=e[i];
if(dist[j]>dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
if(!st[j]){
q[tt++]=j;
if(tt==N)tt=0;
st[j]=true;
}
}
}
}
}
int main()
{
cin>>t>>c>>s>>de;
memset(h,-1,sizeof h);
while(c--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c),add(b,a,c);
}
spfa();
cout<<dist[de]<<endl;
return 0;
}