本人dijkstra平时不怎么打,一般都用SPFA,用dijkstra求k短路比较方便。
求最短路是图论的一个很基础的问题,学好了,大有益处,听某神犇说,所有题都可以用最短路A掉orz%%%%%
这里放这两个算法的模板,以热浪为例。
SPFA:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 200000;
int head[MAXN],dist[MAXN],nxt[MAXN],st,se,tot=0,n,m;
bool vis[MAXN];
struct Edge
{
int from,to,cost;
}edge[MAXN <<2];
void build(int f,int t,int d)
{
edge[++tot].to = t;
edge[tot].from = f;
edge[tot].cost = d;
nxt[tot] = head[f];
head[f] = tot;
}
queue <int >q;
void spfa(int s)
{
dist[s] = 0;
vis[s] = 1;
q.push(s);
while(!q.empty())
{
int x = q.front();
q.pop();
vis[x] = 0;
for(int i = head[x];i;i = nxt[i])
{
int e = edge[i].to;
if(dist[e] > dist[x] + edge[i].cost)
{
dist[e] = dist[x] + edge[i].cost;
if(!vis[e])
{
vis[e] = 1;
q.push(e);
}
}
}
}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&st,&se);
memset(dist,0x7f,sizeof(dist));
memset(vis,0,sizeof(vis));
for(int i = 1; i <= m; i ++)
{
int aa,bb,cc;
scanf("%d%d%d",&aa,&bb,&cc);
build(aa,bb,cc);
build(bb,aa,cc);
}
spfa(st);
cout << dist[se] <<endl;
return 0;
}
dijkstra:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 200000+5;
int head[MAXN],n,m,s,e,dis[MAXN],tot,nxt[MAXN<<1];
bool vis[MAXN];
struct Edge
{
int from,to,cost;
}edge[MAXN<<1];
struct zt
{
int u,v;
bool operator < (const zt b)const
{
return v > b.v;
};
};
void build(int f,int t,int d)
{
edge[++tot].from = f;
edge[tot].to = t;
edge[tot].cost = d;
nxt[tot] = head[f];
head[f] = tot;
}
priority_queue<zt >q;
void dijkstra(int s)
{
memset(dis,0x7f,sizeof(dis));
dis[s] = 0;
q.push((zt){s,0});
while(!q.empty())
{
int x = q.top().u;
q.pop();
if(vis[x])
continue;
vis[x] = 1;
for(int i = head[x]; i ; i = nxt[i])
{
Edge e = edge[i];
if(dis[e.to] > dis[x]+e.cost)
{
dis[e.to] = dis[x]+e.cost;
q.push((zt){e.to,dis[e.to]});
}
}
}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&s,&e);
for(int i = 1; i <= m; i ++)
{
int aa,bb,cc;
scanf("%d%d%d",&aa,&bb,&cc);
build(aa,bb,cc);
build(bb,aa,cc);
}
dijkstra(s);
printf("%d\n",dis[e]);
return 0;
}