Templates - graph theory - graph traversal and storage

FIG right side of the chain with a deposit before the star method, (especially when a plurality of sets of data) and time efficiency slightly higher than vector space saving, a drawback is not easy for a side point to re-sort, when the parallel sides it does not matter when choosing this method is very wise. The biggest problem before the chain to keep the star chart method is to remember to reserve space reverse side.

Map storage and traverse the parent-child relationship of the search tree in fact generally not very important in the figure. Note The following code is no vis emptying , because in fact, not every search will need to be emptied before, sometimes there are some other operations (especially directed graph). Dijkstra algorithm needs to find the right side of the tube just fine.

struct Graph {
    static const int MAXN = 200000;
    static const int MAXM = 400000;

    int n;
    int head[MAXN + 5], top;

    struct Edge {
        int v, w, next;
    } edge[MAXM + 5];

    void Init(int _n) {
        n = _n;
        top = 0;
        memset(head, 0, sizeof(head[0]) * (n + 1));
    }

    void AddEdge(int u, int v, int w) {
        edge[++top].next = head[u];
        edge[top].v = v;
        edge[top].w = w;
        head[u] = top;
    }

    bool vis[MAXN + 5];
    void dfs(int u, int w) {
        vis[u] = 1;
        for(int i = head[u]; i; i = edge[i].next) {
            int v = edge[i].v;
            if(vis[v])
                continue;
            dfs(v, edge[i].w);
        }
    }

    int que[MAXN + 5], front, back;
    void bfs(int s) {
        front = 1, back = 0;
        vis[s] = 1;
        que[++back] = s;
        while(front <= back) {
            int u = que[front++];
            for(int i = head[u]; i; i = edge[i].next) {
                int v = edge[i].v;
                if(vis[v])
                    continue;
                vis[v] = 1;
                que[++back] = v;
            }
        }
    }
} G;

Storage and traversing the tree, dfs the parent node p with the number, the tree will not usually need any bfs, and the distance is unique.

struct Graph {
    static const int MAXN = 200000;
    static const int MAXM = 400000;

    int n;
    int head[MAXN + 5], top;

    struct Edge {
        int v, w, next;
    } edge[MAXM + 5];

    void Init(int _n) {
        n = _n;
        top = 0;
        memset(head, 0, sizeof(head[0]) * (n + 1));
    }

    void AddEdge(int u, int v, int w) {
        edge[++top].next = head[u];
        edge[top].v = v;
        edge[top].w = w;
        head[u] = top;
    }

    void dfs(int u, int p, int w) {
        for(int i = head[u]; i; i = edge[i].next) {
            int v = edge[i].v;
            if(v == p)
                continue;
            dfs(v, u, edge[i].w);
        }
    }
} G;

Guess you like

Origin www.cnblogs.com/KisekiPurin2019/p/12045911.html