个人想法
研究了一下spfa和dijkstra,虽然dijkstra快,而且时间效率高,比较稳点,但是写个模板真的要写好多,我感觉好烦,我去,网上看了一下spfa,其实跟用优先队列优化的dijkstra没什么特别大的区别,但是spfa可以解决有负边出现的问题,应用范围比dijkstra广,所以我又打算搞一个spfa的模板。。不容易呀!!
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 205;
const int INF = 0x3f3f3f3f;
struct Edge
{
int to,next,dist;
}e[2005];
int pre[maxn],dis[maxn],vis[maxn];
void spfa(int s,int t)
{
memset(vis,0,sizeof(vis));
memset(dis,INF,sizeof(dis));
dis[s] = 0;
vis[s] = 1;
queue <int> q;
q.push(s);
while(!q.empty())
{
int u = q.front(); q.pop();
vis[u] = 0;
for(int i = pre[u]; i != -1; i = e[i].next)
{
int v = e[i].to;
if(dis[v] > dis[u] + e[i].dist)
{
dis[v] = dis[u] + e[i].dist;
if(!vis[v])
vis[v] = 1, q.push(v);
}
}
}
if(dis[t] == INF) printf("-1\n");
else printf("%d\n", dis[t]);
}
int main()
{
int n,m;
while(scanf("%d%d", &n, &m) != EOF){
memset(pre,-1,sizeof(pre));
int from,to,dist,s,t;
for(int i = 0; i < 2*m; i += 2){
scanf("%d%d%d", &from, &to, &dist);
e[i].to = to;
e[i].dist = dist;
e[i].next = pre[from];
pre[from] = i;
e[i+1].to = from;
e[i+1].dist = dist;
e[i+1].next = pre[to];
pre[to] = i+1;
}
scanf("%d%d", &s, &t);
spfa(s,t);
}
return 0;
}