今天刚刚开始学习最短路,这道题也就是一道裸的最短路题,狠狠的将这道题敲个各个最短路的模板- -
首先是Dijkstra,这个是n^2的复杂度版本
#include
#include
#include
using namespace std;
const int inf = 1<<30;
int n,m;
int map[300][300];
int vis[300],cast[300];
void Dijkstra(int s,int e)
{
int i,j,min,pos;
memset(vis,0,sizeof(vis));
cast[s] = 0;
vis[s] = 1;
for(i = 0;i
还是Dijkstra,但是这个复杂度为nlogn,当然其优势在这道题并不明显,数据量太小
#include
#include
#include
#include
using namespace std;
const int inf = 1<<30;
const int L = 1000+10;
struct Edges
{
int x,y,w,next;
};
struct node
{
int d;
int u;
node (int dd = 0,int uu = 0):d(dd),u(uu) {}
bool operator < (const node &x) const
{
return u>x.u;
}
};
priority_queue Q;
Edges e[L<<2];
int head[L];
int dis[L];
int vis[L];
void AddEdge(int x,int y,int w,int k)
{
e[k].x = x,e[k].y = y,e[k].w = w,e[k].next = head[x],head[x] = k++;
e[k].x = y,e[k].y = x,e[k].w = w,e[k].next = head[y],head[y] = k++;
}
void init(int n,int m)
{
int i;
memset(e,-1,sizeof(e));
for(i = 0; i
然后是Floyd,这个算法写起来比较简单,但是复杂度为n^3,,花费时间太多了
#include
#include
#include
using namespace std;
const int inf = 100000000;
int map[205][205];
void Floyd(int n)
{
int i,j,k;
for(i = 0;i
SPFA有两个版本,首先是堆栈的实现
#include
#include
#include
using namespace std;
const int inf = 1<<30;
const int L = 2000+10;
struct Edges
{
int x,y,w,next;
}e[L<<2];
int head[L];
int dis[L];
int vis[L];
int relax(int u,int v,int c)
{
if(dis[v]>dis[u]+c)
{
dis[v] = dis[u]+c;
return 1;
}
return 0;
}
void AddEdge(int x,int y,int w,int k)
{
e[k].x = x,e[k].y = y,e[k].w = w,e[k].next = head[x],head[x] = k++;
e[k].x = y,e[k].y = x,e[k].w = w,e[k].next = head[y],head[y] = k++;
}
void init(int n,int m)
{
int i;
memset(e,-1,sizeof(e));
for(i = 0; i
还是SPFA,这次是队列的实现
#include
#include
#include
#include
using namespace std;
const int inf = 1<<30;
const int L = 2000+10;
struct Edges
{
int x,y,w,next;
}e[L<<2];
int head[L];
int dis[L];
int vis[L];
int cnt[L];
int relax(int u,int v,int c)
{
if(dis[v]>dis[u]+c)
{
dis[v] = dis[u]+c;
return 1;
}
return 0;
}
void AddEdge(int x,int y,int w,int k)
{
e[k].x = x,e[k].y = y,e[k].w = w,e[k].next = head[x],head[x] = k++;
e[k].x = y,e[k].y = x,e[k].w = w,e[k].next = head[y],head[y] = k++;
}
void init(int n,int m)
{
int i;
memset(e,-1,sizeof(e));
for(i = 0; i Q;
Q.push(src);
vis[src] = 1;
cnt[src]++;
while(!Q.empty())
{
int u,v;
u = Q.front();
Q.pop();
vis[u] = 0;
for(i = head[u];i!=-1;i=e[i].next)
{
v = e[i].y;
if(relax(u,v,e[i].w)==1 && !vis[v])
{
Q.push(v);
vis[v] = 1;
}
}
}
}
int main()
{
int n,m,i,j,x,y;
while(~scanf("%d%d",&n,&m))
{
init(n,m);
scanf("%d%d",&x,&y);
SPFA(x);
printf("%d\n",dis[y]==inf?-1:dis[y]);
}
return 0;
}