Dijkstra+dfs Template Summary

Source: Internet
Author: User

The primary use of Dijstra is that on the basis of the first ruler there are three angles: Benquan: c[maxn] = {MAXN}, COST[MANX][MAXN] = {inf}; Point right: W[maxn] = {0}, Weight[maxn] = {0}; Shortest Path Bar number: Num[maxn] = {0};

A1003.cpp used two of them as a template to practice deliberately, and to practice how to structure the problem, templating.

Additional side-right code, not the problem, but added to make it complete.

#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int MAXV = 510;

Maximum vertex number const int inf = 1 << 30; int G[MAXV][MAXV], WEIGHT[MAXV],COST[MAXV][MAXV]; Define the adjacency matrix deposit method of the graph, the point weight int D[MAXV] = {inf}; Record the shortest distance from the beginning s to u, int n,m,st,ed; N: Top points, M: number of edges int W[MAXV],NUM[MAXV]C[MANV]; W: Record The sum of the maximum point right, num: Shortest path number bool Vis[maxv] = {false}; Whether the tag has been accessed//The simplest Digestala is to find the shortest path, the final effect is to update the D array,//But in the process of producing the D array, the interesting things are happening void Dijkstra (int s) {//Initialize fill (d , D + MAXV, INF);
    Fill (num,num + maxv, 0);
    Fill (w,w + maxv, 0);
    D[s] = 0; 
    W[s] = Weight[s]; 

    Num[s] = 1;
        loop n for (int i = 0; i < n; i++) {//Find u and min int u =-1, MIN = INF;
                for (int j = 0; J < N; j +) {if (vis[j] = False && D[j] < MIN) {
                U = j;
            MIN = D[j]; } if (U = = 1) return; Vis[u is not found] = true; If you find it, mark it as already.Access//optimization path length for (int v = 0; v < n; v++) {if (vis[v] = = False && G[u][v]!= INF) {if (D[u] + G[u][v] < D[V])//This condition takes off to use {d[v] = D[u] + g[u][v]; Cover C[v] = C[u] + cost[u][v]; Supplemental Benquan W[v] = W[u] + weight[v]; The weight of the shortest path is larger num[v] = Num[u];
                The only one of the three underlying issues that uses the concept of inheritance} else if (D[u] + g[u][v] = = D[v]//Shortest path has the same, then the right to see the sum of {if (W[u] + weight[v] > W[v]) {W[v] = W[u] + Weig
                    HT[V];
                                                } if (C[u] + Cost[u][v] < C[v]) {
                                        C[V] = C[u] + cost[u][v]; 
                } Num[v] + = Num[u];
    }        int main () {scanf ("%d%d%d%d", &n, &m, &st, &ed);
    for (int i = 0; i < n; i++) {scanf ("%d", &weight[i]);
    int u, v; Fill (g[0],g[0] + MAXV * MAXV, INF);//Initialize two-dimensional array in the notation for (int i = 0; i < m; i++) {scanf ("%d%d", &u, &am
        P;V);
    scanf ("%d", &g[u][v]); Read into the side right g[v][u] = G[u][v];
    } Dijkstra (ST);
    printf ("%d%d\n", num[ed],w[ed]);
return 0; }

In order to understand Dijkstra + DFS, it is necessary to first digest the DFS and the pre-record array in the first ruler, and then better understand the Dijkstra + DFS approach under multiple rulers.

The void DFS (int s, int v)//S is the start number, and V is the currently accessed vertex number, which is intended to seek the path of S to v
{
    //If the pre array is ready, pre[i] = i, Initialization is itself a precursor (Lenovo and look-up)
    //recursive boundary
    if (v = =)
    {
        printf ("%d\n", s);
        return;
    }
    DFS (S,pre[v]);
    printf ("%d\n", v);
}

Simply using the design logic of recursive functions to understand this problem, it would be simple: a recursive boundary: v = =, where the beginning and end coincide, naturally to output, and to end the recursion of this layer function: The starting point is fixed, and the second function is the end move forward to the precursor logic: recursion comes back, To output the number of the current node

The scenario of solving problems with Dijkstra + DFS combination is more complicated than the logic to be dealt with in Dijikstra, the complex logic here is not Dijkstra itself, the Dijkstra framework is very simple and beautiful and the code is good to write.

This approach also accords with the idea of separation of concerns if you only record all the shortest paths in Dijkstra, and then find the optimal path in DFS based on the other rulers.

So, first look at the first question: How to record all the shortest paths in Dijkstra.

Vector<int> PRE[MAXN]//storage of multiple shortest paths: only on the first ruler-distance

In the pre array, which records multiple shortest paths, you start without initialization and see the code clearer:

if (D[u] + G[u][v] < D[v])
{
    D[v] = D[u] + g[u][v];
    Pre[v].clear (); Empty, at this time find better
    pre[v].push_back (u); 
} else if (D[u] + g[u][v] = = D[v])
{
    pre[v].push_back (U);
}

As for why empty the Pre[v] array when finding a smaller distance, because Pre[v] is a pioneer with the smallest vertex distance of V, it is now found that smaller, meaning the original record of the predecessor is useless, natural emptying. Also because of this, the pre array begins without initialization.

Now that the array is ready, start writing DFS traversal all the shortest paths and choose the best according to the other rulers.

int optvalue;
Vector<int> PRE[MAXV];
vector<int> path, TempPath;
void DFS (int v)
{
    if (v = st)//ST is the starting point
    {
        temppath.push_back (v);//The Last face of the temporary path TempPath is added to the start St
        int Value The second ruler value that holds the temporary path is
        computed TempPath value
        if (value is better than Optvalue)
        {
            optvalue = value;
            Path = TempPath;
        }
        Temppath.pop_back ();
        return;
    }
    Temppath.push_back (v); Adds the current access node to the temporary path TempPath the last face for
    (int i = 0; i < pre[v].size (); i++)
    {
        DFS (pre[v][i));
    }
    Temppath.pop_back (), and/or traversing all the predecessor nodes, delete the current node v
}

Notice that push_back and pop_back are in pairs appearing here.

This is the form of accurate recognition of memory, then how to understand it.

In fact, very concise, TempPath store is a path, that is, the need to look at the beginning of St to the current node of a ruler value, TempPath because it is a recursive method, so is inverted: from V to St.

This layer of logic is the first to join V, and then recursive V of the precursor, just the precursor is forward (toward the starting point) to walk. We first ignore the recursion, see the last sentence pop_back, so that we can guarantee the execution of a recursive access to a path, the TempPath is emptied.

As for a pair in the recursive boundary, it is because the logic of this layer is unable to add the starting point to the TempPath, so it needs to be temporarily used, so it is temporarily added in.

So the Dijkstra + DFS template's problem framework and part of the details are set up, and then look at the three basic questions that were first mentioned here how to calculate: the sum of the points and Benquan and the minimum path bars

The simplest is the minimum path bar number: With a global variable num = 0, num++ in the recursive boundary.
The sum of the points and the Benquan is the value of the above template, the specific writing is also very simple, is to traverse the temppath array. Note that path is the optimal solution for the combination of several rulers that exist.

Benquan: note is i > 0
int value = 0;
for (int i = Temppath.size ()-1; i > 0; i++)
{
    int u = temppath[i], v = temppath[i-1];
    Value + + g[u][v];//G[u][v] is a side right
}
//point right and
int value = 0;
for (int i = Temppath.size ()-1; I >= 0; i++)
{
    int u = temppath[i];
    Value + + weight[u];//weight is a side right
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.