当前位置:网站首页>2022.02.14
2022.02.14
2022-06-29 06:02:00 【weisir1】
I didn't learn anything new today , I finished the problem set . I will summarize the single source shortest path algorithm and optimization .
First we have to understand its idea , It must be single source , The second is to find the shortest distance from a fixed point to another point .
And there can be no negative weight edge .
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
const int N = 210;
const int INF = 0x3f3f3f3f; // infinity , Not adjacent is infinite
int G[N][N], dis[N]; // G Is the adjacency matrix ,dis Single source to i A weight
int p[N]; // Record the precursor
bool book[N]; // Determine whether it has been added to the set , The set represents the updated nodes
int n;
void dijkstra(int u, int n) // u It's the source , The shortest path from the source point to each vertex ,n It's a fixed number
{
for (int i = 1; i <= N; i++) // initialization
{
dis[i] = G[u][i];
book[i] = 0;
/*
if (dis[i] == INF) // If it is equal to INF, Express u Can't reach this vertex , The precursor is -1
p[i] = -1;
else
p[i] = u;
*/
}
dis[u] = 0; // u To u A weight of 0
book[u] = 1; // Express u Updated
for (int i = 1; i < n; i++) // Find the smallest and update dis
{
// printf("=============\n");
int min = INF, t = u;
for (int j = 1; j <= n; j++)
if (!book[j] && dis[j] < min) // If j Not updated and adjacent
{
min = dis[j];
t = j;
}
if (t == u) // Optimize
return;
book[t] = 1;
// printf("t:%d\n", t);
for (int j = 1; j <= n; j++)
{
if (!book[j] && dis[j] > dis[t] + G[t][j]) // If a vertex is at the same time and u and t Adjacency , Update dis[j] Value
{
// printf("dis[j]:%d\n", dis[j]);
dis[j] = dis[t] + G[t][j];
// p[j] = t; // change j The precursor of t
// printf("dis[j]:%d\n", dis[j]);
}
}
}
}
int main()
{
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
G[i][j] = INF;
cin >> n;
for (int i = 1; i <= n - 1; i++)
for (int j = i + 1; j <= n; j++)
cin >> G[i][j];
dijkstra(1, n);
cout << dis[3] << endl;
}This is dijkstra The template of , While seeking the shortest path, it also saves its precursor , It is convenient to change the output path .
It's not hard to understand , Mainly for dijkstra The optimization of the , There are two ways to optimize , One is heap optimization , The other is chain forward star optimization , These two optimizations optimize the simple from different angles dijkstra Algorithm , So as to reduce the time complexity . Add here dijkstra The time complexity of the naive algorithm is O(n^2), If we use the optimized algorithm , It can make the time complexity reach nlogn The level of . Let me explain the principle and process of optimization .
The first is heap optimization .
Heap optimization refers to the operation of using the priority queue to stack our edges and weights . Priority queues are different from the queues we normally use , Priority queue at C++ in STL Overloads are defined in the container , When we use it, we sort by default , It consists of a large top pile and a small top pile . The two sorts mean that the top elements of the stack are different . The top layer of the big top stack must be the largest , On the contrary, the small top pile is the smallest . The sorting method is the construction of balanced binary tree through array . This means that no matter how many layers we construct , You only need to traverse each time you sort logn The corresponding position can be found and exchanged , Ensure the nature of our priority queue . So if we use priority queues , You can optimize in the search section , Reduce time complexity .
The second is the chain forward star .
This chained forward star is a chained structure simulated by an array
void add(int u, int v, int w)
{
to[++cnt] = v;
val[cnt] = w;
next1[cnt] = head[u]; // Reverse storage , It doesn't affect the result
head[u] = cnt;
}Using arrays next To store the edges that share the starting vertex with it , for instance 1->2,1->5 So when storing ,2 and 5 Will be linked , The advantage of this is to reduce the use of adjacency matrix .
边栏推荐
- 51 single chip microcomputer learning notes 7 -- Ultrasonic Ranging
- Slot
- Structure training camp module II operation
- (practice C language every day) matrix
- What if the hard disk fails to recognize how to recover data
- 2022 recommended precious metal industry research report industry development prospect market analysis white paper (the attachment is a link to the online disk, and the report is continuously updated)
- Blip: conduct multimodal pre training with cleaner and more diverse data, and the performance exceeds clip! Open source code
- Two houses with different colors and the farthest distance
- 2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin copper (no2tmpp) Cu) /2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin (no2tmpp) H2) Qiyue porphyrin supply
- Maximum ascending subarray sum of leetcode simple problem
猜你喜欢

Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin

Agile invincible event

2022 recommended REITs Industry Research Report investment strategy industry development prospect market analysis (the attachment is a link to the online disk, and the report is continuously updated)

Internet enterprises need CRM software to help

Programming specification and variables of shell script

How to use thread stack location

Test Development - ten years of sharpening one sword (VII) interface test tool postman

HTTP Caching Protocol practice

Installing modules in pycharm

VLAN experiment
随机推荐
Rearrangement string of leetcode simple question
Creation of Arduino uno development environment
In 2022, I haven't found a job yet. I have been unemployed for more than one year. What is the "old tester" for eight years?
想问问,券商选哪个比较好尼?本人小白不懂,现在网上开户安全么?
5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin ((tdmpp) H2) /2-nitro-5,10,15,20-tetra (3,5-dimethoxyphenyl) porphyrin copper (no2tdmpp) Cu) supplied by Qiyue
Two houses with different colors and the farthest distance
Go compile source code (window environment)
The win11 file resource manager has an explicit Caton, and Microsoft promises to improve the performance in 2022
Tcapulusdb Jun · industry news collection (VI)
New d reflection generates ABI of C for class
Difference between parametric continuity and geometric continuity
CodeIgniter active record not equal - CodeIgniter active record not equal
HTTP Caching Protocol practice
Rich material libraries make modeling easy and efficient for developers
3 frequently tested SQL data analysis questions (including data and code)
Design risc-v processor from scratch -- data adventure of five stage pipeline
Parsing rshub document auto generation API
AttributeError: module ‘torch. nn. Parameter 'has no attribute' uninitializedparameter 'solution
[high concurrency] deeply analyze the callable interface
Internet enterprises need CRM software to help