一、最短路:
1.Floyd
int V, E;
int d[MAX_V][MAX_V];
void Floyd-Warshall()
{
for(int k = 1; k <= V; k+ +)
for(int i = 1; i <= V; i ++)
for(int j = 1; j <= V; j ++)
d[i][j] = min(d[i][j],d[i][k] + d[k][j]);
}
2.Dijkstra
<pre name="code" class="cpp">struct zt{
int u, v;
bool operator < (const zt&b)const
{
return v > b.v;
}
};
priority_queue<zt> q;
void dijkstra(int s)
{
d[s] = 0;
q.push((zt){s,0});
while(!q.empty())
{
zt x = q.top();
q.pop();
int u = x.u ;
done[u] = 1;
for(int i = first[u]; i != -1; i = next[i])
{
int v = es[i].to ;
if(d[v] > d[u] + es[i].cost )
{
d[v] = d[u] + es[i].cost ;
q.push((zt){v,d[v]});
}
}
}
}
3.Bellman_Ford
int V, E;
int d[233333];
struct edge{
int from, to, cost;
};
edge es[23333];
void Bellman_Ford(int s)
{
for(int i = 1;i <= V;i ++)
d[i] = 0x7fffffff;
d[s] = 0;
while(true)
{
bool bh = 0;
for(int i = 1; i <= E;i ++)
{
edge e=es[i];
if(d[e.from] != 0x7fffffff && d[e.to] > d[e.from] + e.cost){
d[e.to] = d[e.from] + e.cost;
bh = 1;
}
}
if(!bh) break;
}
}
进化——SPFA!
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 10000 + 5 ;
int n,m,a,b,c,xw,tot;
int first[maxn],next[maxn<<1],d[maxn<<2];
bool used[maxn],vis;
struct edge{
int from,to,cost;
}es[maxn<<1];
void build(int f,int t,int d)
{
es[++tot]=(edge){f,t,d};
next[tot]=first[f];
first[f]=tot;
}
queue<int>q;
void spfa(int s)
{
d[s]=0;
q.push(s);
used[s]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
used[u]=0;
for(int i=first[u];i!=-1;i=next[i])
{
int v=es[i].to;
if(d[v]>d[u]+es[i].cost)
{
d[v]=d[u]+es[i].cost;
if(!used[v])
{
q.push(v);
used[v]=1;
}
}
}
}
}