您的位置:首页 > 其它

2013寒假ACM集训_最短路

2013-02-27 11:21 525 查看
一、单源最短路

1、正权

dijkstra

2、任意权

2、1 bellman-ford

2、2 spfa

二、任意点之间最短路

floyd

三、最短路的应用:差分约束系统

参考模板

http://www.toposort.com/blog/shortest-path.html

贴一个新的最新的 spfa模板:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#define LL __int64
const int maxm = 2e6 + 10;
const int maxn = 5e5 + 10;
const int INF = 1<<28;
using namespace std;
int cnt, head[maxn], d[maxn], vis[maxn], n, m;

struct node
{
int v, w, next;
}edge[2*maxm];

void add(int u, int v, int w)
{
edge[cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
};

void spfa(int s)
{
queue<int>q;
int i, u, v;
for(i = 0; i <= n; i++)
d[i] = INF;
d[s] = 0;

q.push(s);

vis[s] = 1;
while(!q.empty())
{
u = q.front();
q.pop();
vis[u] = 0;
for(i = head[u]; i != -1; i = edge[i].next)
{
v=edge[i].v;
if(d[u] + edge[i].w < d[v])
{
d[v] = d[u] + edge[i].w;
if(!vis[v])
{
vis[v] = 1;
q.push(v);
}
}
}
}
};
int main()
{
int  i;
int a, b, w;
int s, t;
while(~scanf("%d%d", &n, &m))
{
cnt = 0;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
for(i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &w);
add(a, b, w);
add(b, a, w);
}
scanf("%d%d", &s, &t);
spfa(s);
printf("%d\n", d[t]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: