最短路合集

三种

1.Floyd复杂度高,可求多源最短路,可有负边权,本质是DP

2.SPFA复杂度容易被坑,单源最短路,可有负边权

3.dijkstra复杂度好,单源最短路,无负边权

SPFA容易被卡数据,一般用dijkstra

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<vector>
 4 #include<queue>
 5 #define N 10002
 6 #define M 1000002
 7 #define inf 2147483647
 8 using namespace std;
 9 struct edge
10 {
11   int v,w;
12   edge(){}
13   edge(int _v,int _w):v(_v),w(_w)
14   {}
15 };
16 int n,m,s;
17 bool inq[N];
18 long long dis[N];
19 queue<int>q;
20 vector<edge>e[N];
21 int cnt[N];
22 void add(int u,int v,int w)
23 {
24   e[u].push_back(edge(v,w));
25 }
26 int main()
27 {
28     scanf("%d%d%d",&n,&m,&s);
29     for(int i=1,u,v,w;i<=m;i++)
30       {
31         scanf("%d%d%d",&u,&v,&w);
32         add(u,v,w);
33       }
34     for(int i=1;i<=n;i++) dis[i]=inf;
35     q.push(s);
36     inq[s]=1;
37     dis[s]=0;
38     //O(km) k<=4 SPFA
39     while(!q.empty())
40     {
41       int t=q.front();
42       inq[t]=0;
43       q.pop();
44       for(int i=0;i<e[t].size();i++)
45         {
46         if(dis[t]+e[t][i].w<dis[e[t][i].v])
47           {
48             dis[e[t][i].v]=dis[t]+e[t][i].w;
49             if(!inq[e[t][i].v]) q.push(e[t][i].v),inq[e[t][i].v]=1;
50           }
51         }
52     }
53     for(int i=1;i<=n;i++) printf("%lld ",dis[i]);
54     return 0;
55 }

SPFA

#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 2005;
const int M = 2e5 + 5;
double dis[N];
bool vis[N];
struct edge
{
  int to, next;
  double w;
} e[M];
int head[N], cnt;
int n, m;
void add(int u, int v, double w)
{
  e[++cnt].w = w;
  e[cnt].to = v;
  e[cnt].next = head[u];
  head[u] = cnt;
}
void dijkstra(int x)
{
  for (int i = 1; i <= n; i++)
    dis[i] = 0;
  dis[x] = 1;
  for (int i = 1; i <= n; i++)
  {
    int p = 0;
    for (int j = 1; j <= n; j++)
    {
      if (!vis[j])
        if (p == 0 || dis[j] > dis[p])
          p = j;
    }
    vis[p] = 1;
    for (int j = head[p]; j; j = e[j].next)
      if (!vis[e[j].to] && dis[p] * e[j].w > dis[e[j].to])
        dis[e[j].to] = dis[p] * e[j].w;
  }
}
int main()
{
  scanf("%d%d", &n, &m);
  for (int i = 1, u, v, w; i <= m; i++)
  {
    scanf("%d%d%d", &u, &v, &w);
    add(u, v, 1 - w / 100.00);
    add(v, u, 1 - w / 100.0);
  }
  int p, q;
  scanf("%d%d", &p, &q);
  dijkstra(p);
  printf("%.8lf\n", 100 / dis[q]);
  return 0;
}

dijkstra

上一篇:Dijkstra


下一篇:数据结构/PTA-旅游规划/图/dijkstra算法