C++ – Basic operations on trees and graphs

peer to peer

Create an array, use subscripts to represent different points, and use its content to represent the points connected to this point. For example, if the array is named graph, then graph[0] = 1 can be used to indicate that point 0 can lead to point 1.

Among them, if a point can be connected to multiple points, it can be stored in a two-dimensional array. For example, graph[0][0] = 1 and graph[0][1] = 2 means that the point connected to point 0 has 1 point and 2:XNUMX. Normally, the second dimension of this XNUMXD array will not be filled, so you can use a vector as the second dimension, like this:

#include <vector>
using namespace std;
const int MAXN = 1e6 + 100;

int main() {
    vector<int> graph[MAXN]; 
    return 0;
}

Such storage looks like this:

PS: This method is not suitable for storing images with rights.

adjacency matrix

Use a two-dimensional array to store data on relationships (edges or arcs) between vertices. This two-dimensional array is called an adjacency matrix. The adjacency matrix is ​​divided into a directed graph adjacency matrix and an undirected graph adjacency matrix. (For undirected graphs, the adjacency matrix must be symmetric) For example, graph[0][1] = 1 means that there is an edge between point 0 and point 1, with a weight of 1.

In adjacency matrices, self-to-self weights are often stored as 0 or negative numbers, such as graph[0][0] = 0. If there is no edge between two points, it is always saved as MAX_DATA. (MAX_INT = 0x7FFFFFFFF)

using namespace std;
const int MAXN = 1e6 + 100;
const int MAX_INT = 0x7FFFFFFF;

int main() {
    int graph[MAXN][MAXN];
    return 0;
}

Such storage looks like this:

Post Reply