HDU 1874 Shortest Path Spfa

Needless to say, it is the same question as the previous algorithms, because I just learned the shortest way, so I will use this very simple template question to familiarize myself with these four algorithms, hahaha. .

 This time is the last algorithm I learned about the shortest path.

Spfa algorithm:

            Use queue simulation, take out the element at the head of the queue, find the point adjacent to the head of the queue each time, see if it can be relaxed, and update the dis array. If some adjacent points are already in the queue, there is no need to join the queue. The point that is not in the queue (the point adjacent to the head of the fetched queue) makes it enqueue, then look for it, and then enqueue...until the queue is empty.

            Finally output dis[target point] on it. . .

Topic link: Click to open the link

Code:

   

#include <stdio.h>
#include <queue>
using namespace std;
const int manx = 210 ;
const int inf  = 0xfffff;

int n, m, map[manx][manx], vis[manx], dis[manx];

void Spfa (int x){
    for (int i =0 ; i < n; i++){
        dis[i] = inf ;
        show [i] = 0;
    }
    queue <int> que;
    dis[x] = 0;
    screw[x] = 1;
    que.push (x);
    while (!que.empty()){
        int temp = que.front ();
        that.pop();
        vis[temp] = 0;
        for (int i = 0; i < n; i++){
            if (dis[i] > dis[temp] + map[temp][i]){
                dis[i] = dis[temp] + map[temp][i];
                if (!vis[i]){
                    show [i] = 1;
                    que.push (i);
                }
            }
        }
    }
}

int main() {
    int a, b, price ;
    while (~scanf("%d%d",&n, &m)){
        for (int i =0 ;i < n; i++){
            for (int j = 0; j < n; j++){
                map[i][j] = (i == j) ? 0 : inf ;
            }
        }
        for (int i = 0; i < m ; i++){
            scanf("%d%d%d",&a, &b, &price);
            if (map[a][b] > price){
                map[a][b] = map[b][a] = price ;
            }
        }
        int x, y;
        scanf("%d%d", &x, &y);
        Spfa(x);
        if (dis[y] < inf ){
            printf("%d\n", dis[y]);
        }
        else{
            printf("-1\n");
        }
    }
    return 0;
}

Wow wow wow, I have finally completed these four algorithms, but I am still unfamiliar with them, and I have to continue to do some questions to consolidate, and the first three algorithms are basically implemented using adjacency matrices. I heard that you can also use adjacency lists, although I Not yet. . Really a dish, ashamed. However, I will learn to use the adjacency list to implement it in the future. After all, if the adjacency list is used, there will be some optimizations in time! Come on!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325885191&siteId=291194637
Recommended