最短路径问题 (最短路模板)

【题目描述】

    平面上有n个点(n≤100),每个点的坐标均在-10000~10000之间。其中的一些点之间有连线。若有连线,则表示可从一个点到达另一个点,即两点间有通路,通路的距离为两点间的直线距离。现在的任务是找出从一点到另一点之间的最短路径。

【题目链接】

    http://ybt.ssoier.cn:8088/problem_show.php?pid=1342

【代码1】Floyd算法 O(n3

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n,i,j,m,a,b,k,src,dst;
 4 pair<int,int> v[110];
 5 double d[110][110];
 6 int main()
 7 {
 8     memset(d,127,sizeof(d));
 9     scanf("%d",&n);
10     for(i=1;i<=n;i++) scanf("%d%d",&v[i].first,&v[i].second);
11     scanf("%d",&m);
12     for(i=1;i<=m;i++)
13         scanf("%d%d",&a,&b),d[a][b]=
14         d[b][a]=sqrt((v[a].first-v[b].first)*(v[a].first-v[b].first)+
15                      (v[a].second-v[b].second)*(v[a].second-v[b].second));
16     scanf("%d%d",&src,&dst);
17     for(k=1;k<=n;k++)
18         for(i=1;i<=n;i++)
19             for(j=1;j<=n;j++)
20                 d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
21     printf("%.2f\n",d[src][dst]);
22     return 0;
23 }

【代码2】Dijkstra算法O(n2

 1 #include <bits/stdc++.h>
 2 #define P pair<int,int>
 3 using namespace std;
 4 P ver[110];
 5 int n,m,i,j,src,dst,p1,p2;
 6 int v[110];
 7 double G[110][110],d[110];
 8 double calc(int a,int b)
 9 {
10     return sqrt((ver[a].first-ver[b].first)*(ver[a].first-ver[b].first)+
11                 (ver[a].second-ver[b].second)*(ver[a].second-ver[b].second));
12 }
13 void dijkstra()
14 {
15     int i,j,x;
16     memset(d,0x7f,sizeof(d));
17     d[src]=0;
18     for(i=1;i<n;i++) {
19         x=0;
20         for(j=1;j<=n;j++)
21             if(!v[j]&&(x==0||d[j]<d[x])) x=j;
22         v[x]=1;
23         for(j=1;j<=n;j++)
24             d[j]=min(d[j],d[x]+G[x][j]);
25     }
26 }
27 int main()
28 {
29     memset(G,0x7f,sizeof(G));
30     scanf("%d",&n);
31     for(i=1;i<=n;i++) scanf("%d%d",&ver[i].first,&ver[i].second);
32     scanf("%d",&m);
33     for(i=1;i<=m;i++) scanf("%d%d",&p1,&p2),G[p1][p2]=G[p2][p1]=calc(p1,p2); 
34     scanf("%d%d",&src,&dst);
35     dijkstra();
36     printf("%.2f\n",d[dst]);
37     return 0;
38 }

【代码3】dijkstra算法堆优化 O((m+n)log(n))

【代码4】Bellman-Ford算法 O(m*n)

【代码5】Spfa(shortest path fast algorithm)O(km)

猜你喜欢

转载自www.cnblogs.com/Willendless/p/9427908.html