[AcWing 1128] 信使

image
image

求起点到其他所有点的最短距离

堆优化 \(dijkstra\)\(20 \ ms\)

复杂度 \((m \cdot log(n)) = 200 \times log(100) \approx 664\)


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
int h[N], e[N], ne[N], w[N], idx;
int d[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void dijkstra(int sp)
{
    memset(d, 0x3f, sizeof d);
    memset(st, false, sizeof st);
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, sp});
    d[sp] = 0;
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        auto v = t.second;
        if (st[v])
            continue;
        st[v] = true;
        for (int i = h[v]; i != -1; i = ne[i]) {
            int j = e[i];
            if (d[j] > d[v] + w[i]) {
                d[j] = d[v] + w[i];
                heap.push({d[j], j});
            }
        }
    }
}

void solve()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 0; i < m; i ++) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    dijkstra(1);
    int res = 0;
    for (int i = 2; i <= n; i ++)
        res = max(res, d[i]);
    cout << (res == INF ? -1 : res) << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 堆优化 \(dijkstra\) 模板,最后 \(res\) 取所有距离的最大值

Floyd (\(40 \ ms\)

复杂度 \((n^3) = 100^3 = 1 \times 10^6\)


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N = 100 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
int g[N][N];

void solve()
{
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    for (int i = 0; i < m; i ++) {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = g[b][a] = min(g[a][b], c);
    }
    for (int k = 1; k <= n; k ++)
        for (int i = 1; i <= n; i ++)
            for (int j = 1; j <= n; j ++)
                g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
    int res = 0;
    for (int i = 2; i <= n; i ++)
        res = max(res, g[1][i]);
    cout << (res == INF ? -1 : res) << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

posted @ 2022-08-08 23:18  wKingYu  阅读(41)  评论(0)    收藏  举报