poj1797 spfa 最短路

題目鏈接:點擊打開鏈接


題意:

給一個無向圖,每條邊有個能承受的重量;

問從1到n的最大通過的重量;


理解:

這是以前比賽的一個題;

當時用的多個最短路,最後超時;

實際上在最短路的遞推式上改一下就行了;

d[v] = max(d[v], min(d[u], w[u, v]));
用這個遞推式就可以求出最後的答案;

實際上跟求最短路是一樣的;


剛學的spfa用上去很好;

實際上它用隊列只維護了每個點;

而對於前向星存圖也很有趣;

用起來都很不錯;


代碼如下:


#include <cstdio>
#include <cstring>
#include <cmath>

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>

using namespace std;

typedef long long LL;

const int MAXN = 1e6 + 10;
const int MOD = 1e9 + 7;
const int INF = 0x7fffffff;
const int N = 10000000;

typedef pair<int, int> PII;

#define X first
#define Y second

const int MAXE = MAXN;
const int MAXV = 1011;

struct node {
    int to, next, cost;
}e[MAXE];

int head[MAXV], tot;
int n, m;

void init() {
    memset(head, -1, sizeof head);
    tot = 0;
}

void add_edge(int u, int v, int cost) {
    e[tot].to = v;
    e[tot].next = head[u];
    e[tot].cost = cost;
    head[u] = tot++;
}

int dis[MAXV];
int outque[MAXV];
bool vis[MAXV];

bool spfa(int s) {
    for (int i = 1; i <= n; ++i) {
        vis[i] = false;
        dis[i] = -1;
        outque[i] = 0;
    }

    queue<int> que;
    que.push(s);
    dis[s] = INF;
    vis[s] = true;
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        vis[u] = false;
        if (++outque[u] > n) {
            return false;
        }
        for (int i = head[u]; i != -1; i = e[i].next) {
            int v = e[i].to;
            int cost = min(dis[u], e[i].cost);
            if (dis[v] >= cost) {
                continue;
            }
            dis[v] = cost;
            if (vis[v] == true) {
                continue;
            }
            vis[v] = true;
            que.push(v);
        }
    }
    return true;
}

int main() {
    int t;
    cin >> t;
    for (int I = 1; I <= t; ++I) {
        cin >> n >> m;
        init();
        for (int i = 0; i < m; ++i) {
            int u, v, cost;
            scanf("%d%d%d", &u, &v, &cost);
            add_edge(u, v, cost);
            add_edge(v, u, cost);
        }
        spfa(1);
        cout << "Scenario #" << I << ":" << endl;
        cout << dis[n] << endl;
        cout << endl;
    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章