Floyed-Warshall算法

本文深入讲解了Floyd算法,一种用于解决多源最短路径问题的经典算法。文章详细阐述了算法的思想、实现步骤及代码,并通过两个实例展示了如何在不同场景下应用Floyd算法来求解最短路径和判断图中两点是否相连。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类:
多源最短路径算法。

作用:
1.求最短路。 2.判断一张图中的两点是否相连。

优点:
实现极为简单

缺点:
只有数据规模较小且时空复杂度都允许时才可以使用(NOIP上大概不会放出来的吧)。

思想:
3层循环,第一层枚举中间点k,第二层与第三层枚举两个端点i,j。若有dis[i][j] > dis[i][k] + dis[k][j] 则把dis[i][j]更新成dis[i][k] + dis[k][j](原理还是很好理解的)。

实现:
(a)初始化:点i,j如果有边相连,则dis[i][j] = w[i][j]。如果不相连,则dis[i][j] = 0x7fffffff(int极限值),表示两点不相连(或认为相隔很远)。 
(b)算法代码:

for(int k = 1; k <= n; k++)  //枚举中间点(必须放最外层)
  for(int i = 1; i <= n; i++)  //枚举端点i
    if(i != k)
      for(int j = 1; j <= n; j++)  //枚举端点j
        if(i != j && j != k && dis[i][j] > dis[i][k] + dis[k][j])
          dis[i][j] = dis[i][k] + dis[k][j];



(c)算法结束:dis[i][j]得出的就是从i到j的最短路径。

Floyed算法变形:
如果是一个没有边权的图,把相连的两点间距离设为dis[i][j] = true,不相连的两点设为dis[i][j] = false,用Floyed算法的变形:

for(int k = 1; k <= n; k++)  //枚举中间点
  for(int i = 1; i <= n; i++)  //枚举端点i
    if(i != k)
      for(int j = 1; j <= n; j++)  //枚举端点j
        if(i != j && j != k)
          dis[i][j] = dis[i][j] || (dis[i][k] && dis[k][j]);(判断是否相连)


用这个方法可以判断一张图中的两点是否相连。
例题:

一、

 最短路径问题

给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。

Input

输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。 
(1<n<=1000, 0<m<100000, s != t)

Output

输出 一行有两个数, 最短距离及其花费。

Sample Input

3 2
1 2 5 6
2 3 4 5
1 3
0 0

Sample Output

9 11
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>

using namespace std;
#define INF 0x3f3f3f3f

int n,m,s,t;
int a,b,d,p;
int map[1010][1010];
int money[1010][1010];

int main()
{
    while(~scanf("%d%d",&n,&m)){
        if(n==0&&m==0)  break;
        for(int i=1; i<=n; i++)
            for(int j=1;j<=n;j++)
                if(i==j) map[i][j]=0;
                else map[i][j]=INF;
        for(int i=1;i<=m;i++){
            scanf("%d%d%d%d",&a,&b,&d,&p);
            map[a][b]=d;
            money[a][b]=p;
        }
        scanf("%d%d",&s,&t);
        for(int k=1; k<=n; k++)
            for(int i=1; i<=n; i++)
                for(int j=1; j<=n; j++)
                {
                    if(map[i][j]>map[i][k]+map[k][j]){
                        map[i][j]=map[i][k]+map[k][j];
                        money[i][j]=money[i][k]+money[k][j];
                    }


                }


        cout << map[s][t] << " " << money[s][t] << endl;

    }
    //cout << "Hello world!" << endl;
    return 0;
}





https://blog.csdn.net/weixin_43272781/article/details/83307686 

二、Einbahnstrasse

Einbahnstra  e (German for a one-way street) is a street on which vehicles should only move in one direction. One reason for having one-way streets is to facilitate a smoother flow of traffic through crowded areas. This is useful in city centers, especially old cities like Cairo and Damascus. Careful planning guarantees that you can get to any location starting from any point. Nevertheless, drivers must carefully plan their route in order to avoid prolonging their trip due to one-way streets. Experienced drivers know that there are multiple paths to travel between any two locations. Not only that, there might be multiple roads between the same two locations. Knowing the shortest way between any two locations is a must! This is even more important when driving vehicles that are hard to maneuver (garbage trucks, towing trucks, etc.) 

You just started a new job at a car-towing company. The company has a number of towing trucks parked at the company's garage. A tow-truck lifts the front or back wheels of a broken car in order to pull it straight back to the company's garage. You receive calls from various parts of the city about broken cars that need to be towed. The cars have to be towed in the same order as you receive the calls. Your job is to advise the tow-truck drivers regarding the shortest way in order to collect all broken cars back in to the company's garage. At the end of the day, you have to report to the management the total distance traveled by the trucks.

Input

Your program will be tested on one or more test cases. The first line of each test case specifies three numbers (N , C , and R ) separated by one or more spaces. The city has N locations with distinct names, including the company's garage. C is the number of broken cars. R is the number of roads in the city. Note that 0 < N < 100 , 0<=C < 1000 , and R < 10000 . The second line is made of C + 1 words, the first being the location of the company's garage, and the rest being the locations of the broken cars. A location is a word made of 10 letters or less. Letter case is significant. After the second line, there will be exactly R lines, each describing a road. A road is described using one of these three formats: 


A -v -> B 
A <-v - B 
A <-v -> B 


A and B are names of two different locations, while v is a positive integer (not exceeding 1000) denoting the length of the road. The first format specifies a one-way street from location A to B , the second specifies a one-way street from B to A , while the last specifies a two-way street between them. A , ``the arrow", and B are separated by one or more spaces. The end of the test cases is specified with a line having three zeros (for N , C , and R .) 

The test case in the example below is the same as the one in the figure. 

Output

For each test case, print the total distance traveled using the following format: 


k . V 


Where k is test case number (starting at 1,) is a space, and V is the result.

Sample Input

4 2 5
NewTroy Midvale Metrodale
NewTroy   <-20-> Midvale
Midvale   --50-> Bakerline
NewTroy    <-5-- Bakerline
Metrodale <-30-> NewTroy
Metrodale  --5-> Bakerline
0 0 0

Sample Output

1. 80
/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG

using namespace std;
typedef long long ll;
const int N=10000;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,c,r,m;
char  s1[100],s2[100],c1,c2;
char str[1005][100];
int a[105][105];
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int T=0;
    while(scanf("%d%d%d",&n,&c,&r)!=EOF&&n+c+r){
        map<string,int>M;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                a[i][j]=INF;
            }
        }
        for(int i=0;i<=c;i++){
            scanf("%s",str[i]);
        }
        int cnt=0;
        for(int i=1;i<=r;i++){
            scanf("%s %c-%d-%c %s",s1,&c1,&t,&c2,s2);
            if(!M[s1])
                M[s1]=++cnt;
            if(!M[s2])
                M[s2]=++cnt;
            int x=M[s1],y=M[s2];
            if(c1=='<'&&a[y][x]>t)
                a[y][x]=t;
            if(c2=='>'&&a[x][y]>t)
                a[x][y]=t;
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                for(int k=1;k<=n;k++){
//                    if(a[j][k]>a[j][i]+a[i][k])
//                        a[j][k]=a[j][i]+a[i][k];
                        a[j][k]=min(a[j][k],a[j][i]+a[i][k]);
                }
            }
        }
        ll ans=0;
        for(int i=1;i<=c;i++){
            ans+=a[M[str[0]]][M[str[i]]]+a[M[str[i]]][M[str[0]]];
        }
        printf("%d. %lld\n",++T,ans);
    }
    //cout << "Hello world!" << endl;
    return 0;
}

https://blog.csdn.net/weixin_43272781/article/details/84943350

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Starzkg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值