当前位置:网站首页>Shortest path topic
Shortest path topic
2022-07-28 10:29:00 【MJ's Manon space】
shortest path
Floyd-Warshall Algorithm
purpose : Find the shortest path of multiple sources ( That is, the shortest circuit between any two points )

Pictured above , We need the shortest distance between different cities , You can list a simple distance matrix 
And then according to a->b If the distance is less than (a->c)+(c->b) Distance of , Will a->b Replace the distance of with (a->c)+(c->b) The distance logic of .
The core code is as follows :
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(e[i][j]>e[i][k]+e[k][j])
e[i][j]=e[i][k]+e[k][j];
The point to note here is , In the outermost for Of the statement k, Be sure to put it in the middle of the judgment statement .
The disadvantage is that it will cover the original side length , If you need to perform multiple operations , The original side length cannot be retrieved , And negative weight cannot be calculated , Code time complexity O(n3).
Dijkstra Algorithm
The characteristic of the dichhester algorithm is , It increases the vis Array , For relaxation operation , The relaxation operation is also dijkstra The most striking feature , It can greatly reduce the time complexity , Added dis Array , To determine the distance , Instead of covering the original side length , After the operation, the original side length array can still be kept unchanged .
Dijkstra The algorithm is greedy , First save the distance from the starting point to all points to find the shortest , Then relax once and find the shortest , The so-called relaxation operation is , Go through it and see if it will be closer to the shortest point just found as a transfer station , If it's closer, update the distance , In this way, after finding all the points, the shortest distance from the starting point to all other points is saved .

Operate according to such logic
The code example is as follows
void dijk(int s) {
// Calculate all points to s The shortest distance , Deposit in dis In the array
memset(dis, 0x3f, sizeof(dis));// Set the distance to maximum
memset(vis, 0, sizeof(vis));// Initialize to all unrelaxed States
dis[s] = 0;// The distance to oneself is 0
while (1) {
int k = 0;// Find the nearest unrelaxed node
for (int j = 1;j <= n;j++) {
if (!vis[j] && dis[j] < dis[k])
k = j;// Set the nearest unrelaxed node to k
}
if (!k)return;// If there are no recently unrelaxed nodes , Explain all slack , end
vis[k] = 1;// Relaxation complete
for (int j = 1;j <= n;j++) {
if (dis[j] > dis[k] + map[k][j]) {
// Judge , replace dis length
dis[j] = dis[k] + map[k][j];
}
}
}
}
The disadvantage is that negative weight cannot be calculated , Code time complexity O(n2), Using chained forward stars or priority queues for optimization can be optimized as O(nlogn).
Bellman-Ford Algorithm
This algorithm is better than dijkstra It's easier , Reduce the operation of determining relaxation , Relax each point repeatedly , Each relaxation operation , There will be some vertices that have found their shortest path , That is, the shortest path of these vertices “ Estimated value ” Turn into “ Determinate value ”. The advantages are obvious , Negative weight can be calculated , But at the same time, the time complexity will also increase .
Code example :
for(int k = 1 ; k <= n - 1 ; k ++)
{
for(int i = 1 ; i < m ; i ++)
{
if(dis[v[i]] > dis[u[i]] + w[i])
dis[v[i]] = dis[u[i]] + w[i] ;
}
}
Title Example :
President Dongdong wants to marry the Sheikh's daughter , But the chief asked him to give a certain amount of money as a dowry . Besides money , The chief also allowed to use some items of other people in the tribe plus a little money as a dowry . Other people's items can also be obtained by specifying some items of other people plus some money . But everyone in the tribe has a level . The level of people involved in the whole transaction process can only be within a limited difference . Ask the president how much money Dongdong needs at least to marry the Sheikh's daughter . Suppose everyone has only one item .
Input
The first line of input is two integers M,N(1 <= N <= 100), In turn, it represents the status level gap limit and the total number of items . Next, according to the number from small to large, it gives N A description of an object . The description of each item begins with three non negative integers P、L、X(X < N), Show the price of the item in turn 、 Master's rank and total number of substitutes . Next X Each line contains two integers T and V, The number of the substitute and " Favorable Price ".
Output
Output the minimum number of gold coins needed .
Sample Input
1 4
10000 3 2
2 8000
3 5000
1000 2 1
4 200
3000 2 1
4 200
50 2 0
Sample Output
5250
example : The difference between the highest and lowest grades shall not exceed 1, common 4 Items The Sheikh's daughter Grade 3 Ask for cash 10000 element Or items of a +8000 element Or B's items +5000 element Items of a Grade 2 Ask for cash 1000 element Or C items +200 element B's items Grade 2 Ask for cash 3000 element Or C items +200 element C's items Grade 2 Ask for cash 50 element In this case , The minimum cost plan is : Buy C's things (50) Change B's things (+200) For the Sheikh's daughter (+5000) altogether 5250 element .
Code example :
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdio>
#include<set>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<map>
#define ll long long
using namespace std;
const int maxn = 1000;
ll e[1020][1020];
int vis[1020], dis[1020];
ll lv[10000],temp,minn;
int n, m, t, x;
void dijk(int s, int l, int r) {
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[s] = 0;
while (1) {
int k=-1,minn=0x3f3f3f3f;
for (int j = 0;j <= n;j++) {
if (!vis[j] && dis[j] < minn) {
k = j;
minn = dis[j];
}
}
if (k==-1)return;
vis[k] = 1;
for (int j = 0;j <= n;j++) {
if (lv[j] >= l && lv[j] <= r) {
if (dis[j] > dis[k] + e[k][j]) {
dis[j] = dis[k] + e[k][j];
}
}
}
}
}
void Init() {
memset(e, 0x3f3f3f3f, sizeof e);
for (int i = 1;i <= m;i++) {
e[i][i] = 0;
}
}
void input() {
cin >> m >> n;
for (int i = 1;i <= n;i++) {
cin >> e[0][i] >> lv[i] >> t;
for (int j = 1;j <= t;j++) {
cin >> x;
cin >> e[x][i];
}
}
}
int main() {
Init();
input();
int ans = 0x3f3f3f3f;
for (int i = lv[1] - m;i <= lv[1];i++) {
dijk(0, i, i + m);
ans = min(dis[1], ans);
}
cout << ans;
}
边栏推荐
- 2. 输出数组中重复的数字之一
- Summary of key points of bank entry examination
- 4. Adjust the array order so that odd numbers precede even numbers
- 配置树莓派,过程和遇到问题
- C语言 输入带空格的字符串
- 华为入股石墨烯材料厂商富烯科技,持股10%
- Detailed explanation of thread synchronization volatile and synchronized
- 中芯国际科创板IPO顺利过会,市值有望突破2000亿!
- 15. Judge whether the target value exists in the two-dimensional array
- 简介
猜你喜欢

Aqua Data Studio 18.5.0 export insert statement

5、动态规划---斐波那契数列
![Database security - create login user + configure permissions [notes]](/img/02/0c3eb542593e8e0a3a62db75c52850.png)
Database security - create login user + configure permissions [notes]

Get to know SuperMap idesktop for the first time

gcc: error trying to exec 'as': execvp: No such file or directory

Uni app project directory, file function introduction and development specification

SQL Server 2016 学习记录 --- 数据定义

Record a parent-child project in idea, modify the name of project and module, and test it personally!

Typora使用教程

ACM寒假集训#5
随机推荐
11、链表反转
Uni app advanced life cycle
Add new startup logo and startup / shutdown animation in mt6735
2020第二届传智杯初赛
uni-app项目目录、文件作用介绍 及 开发规范
3. Print the linked list in reverse order with the array
Ueeditor v1.4.3 control file compression
Can kingbasees v8r6 JDBC use VIP?
第11届蓝桥杯本科组校赛(20200321)
16、字符串反转
Ie compatibility problem handling
UEditor V1.4.3控制文件压缩
Match file names from file paths using regular expressions
gcc: error trying to exec 'as': execvp: No such file or directory
SQL Server 2016 学习记录 ---视图
ZTE: 5nm 5g base station chip is being introduced!
pt-kill 查询中包含中文字符 导致工具失效的排查
Uni app project directory, file function introduction and development specification
Aqua Data Studio 18.5.0 export insert statement
第一篇:UniAPP的小程序跨端开发-----创建uniapp项目