题解:P15805 [GESP202603 八级] 子图最短路

· · 题解

暴力

暴力枚举 l, r,对于每个 l, r,对在编号 [l,r] 之内的点做 Floyd 算法,时间复杂度 O(n^5),预计得分 40 分。

正解

发现 Floyd 算法内枚举经过点的循环是从小到大的,对暴力解法进行修改:将枚举的经过点当作 r。时间复杂度 O(n^4),预计得分 100 分。实际实现时会有大约 \dfrac{1}{4} 的常数,完全可以通过。

:::info[参考代码]

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 105, mod = 1e9;

int a[N][N];
int n, m;
ll ans;
ll dp[N][N];

void floyd(int L){
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++){
            if(i == j)
                dp[i][j] = 0;
            else if(a[i][j] != 0)
                dp[i][j] = a[i][j];
            else
                dp[i][j] = 1e18;
        }
    for(int R = L; R <= n; R++){ // 枚举 r
        for(int i = L; i <= n; i++)
            for(int j = L; j <= n; j++)
                dp[i][j] = min(dp[i][j], dp[i][R] + dp[R][j]);
        for(int i = L; i <= R; i++) // 统计答案
            for(int j = i; j <= R; j++)
                ans = (ans + dp[i][j]) % mod;
    }
}

signed main(){
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> n >> m;
    for(int i = 1, x, y, z; i <= m; i++){
        cin >> x >> y >> z;
        // 注意会有重边,进行比较
        if(a[x][y] == 0)
            a[x][y] = z;
        else
            a[x][y] = min(a[x][y], z);
        if(a[y][x] == 0)
            a[y][x] = z;
        else
            a[y][x] = min(a[y][x], z);
    }
    for(int i = 1; i <= n; i++) // 枚举 l
        floyd(i);
    cout << ans;

    return 0;
}

:::