三种求最短路径的算法

三种求最短路径的算法

using namespace std;

const int MAX = 1123;
const int INF = 0x3f3f3f3f;

vector<pair<int, int> > edge[MAX];
int dist[MAX];
bool done[MAX];
bool in_que[MAX];

void dij(int s) {
    priority_queue<pair<int, int> > q;
    memset(done, 0, sizeof(done));
    memset(dist, 0x3f, sizeof(dist));
    dist[s] = 0;
    q.push(make_pair(0, s));
    while (!q.empty()) {
        int u = q.top().second;
        q.pop();
        if (done[u]) continue;
        done[u] = true;
        for (int i = 0; i < edge[u].size(); ++i) {
            int v = edge[u][i].first;
            int w = edge[u][i].second;
            if (!done[v] && dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                q.push(make_pair(-dist[v], v));
            }
        }
    }
}

void spfa(int s) {
    queue<int> q;
    memset(in_que, 0, sizeof(in_que));
    memset(dist, 0x3f, sizeof(dist));
    dist[s] = 0;
    q.push(s);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 0; i < edge[u].size(); ++i) {
            int v = edge[u][i].first;
            int w = edge[u][i].second;
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                if (!in_que[v]) {
                    q.push(v);
                    in_que[v] = true;
                }
            }
        }
        in_que[u] = false;
    }
}

int G[MAX][MAX];
void floyd(int n) {
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (G[i][k] + G[k][j] < G[i][j]) {
                    G[i][j] = G[i][k] + G[k][j];
                }
            }
        }
    }
}

int main() {
    int n, m;
    while (cin >> n >> m) {
        memset(G, 0x3f, sizeof(G));
        for (int i = 0; i < n; ++i) {
            G[i][i] = 0;
            edge[i].clear();
        }
        for (int i = 0; i < m; ++i) {
            int u, v, w;
            cin >> u >> v >> w;
            edge[u].push_back(make_pair(v, w));
            edge[v].push_back(make_pair(u, w));
            G[u][v] = G[v][u] = min(w, G[v][u]);
        }
        int s, t;
        cin >> s >> t;
        floyd(n);
        printf("%d\n", G[s][t] == INF ? -1 : G[s][t]);
    }
}

你可能感兴趣的:(三种求最短路径的算法)