--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

洛谷__P6464 [传智杯 #2 决赛] 传送门(Floyd)

题目链接:P6464 [传智杯 #2 决赛] 传送门 - 洛谷


题目大意:

在带权无向连通图中,选两个点建传送门(距离变0),

使得所有点对最短距离之和最小,输出最小值。( 节点 n100 )


思路:

数据很小,直接暴力跑 Floyd 即可,代码有详细注释


代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 108, mod = 998244353;

int n, m;
int e[N][N];
int f[N][N];

void back() {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            f[i][j] = e[i][j];
        }
    }
}

void solve() {

    cin >> n >> m;
    mst(e, 1);
    for (int i = 1; i <= m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        if (e[a][b] > c) e[a][b] = e[b][a] = c;
    }
    
    
    for (int k = 1; k <= n; k++) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == j) continue;
                if (e[i][j] > e[i][k] + e[k][j]) {
                    e[i][j] = e[i][k] + e[k][j];
                }
            }
        }
    }
    
    int res = inf;
    for (int i = 1; i <= n; i++) {//枚举 i->j 的距离缩短为0
        for (int j = 1; j <= n; j++) {
        
            back();//复原!
            
            if (i == j) continue;
            f[i][j] = f[j][i] = 0;
            
            //把缩短后影响到的边跑一遍floyd
            for (int x = 1; x <= n; x++) {
                for (int y = 1; y <= n; y++) {
                    if (f[x][y] > f[x][i] + f[i][y]) {
                        f[x][y] = f[x][i] + f[i][y];
                    }
                }
            }
            
            for (int x = 1; x <= n; x++) {
                for (int y = 1; y <= n; y++) {
                    if (f[x][y] > f[x][j] + f[j][y]) {
                        f[x][y] = f[x][j] + f[j][y];
                    }
                }
            }
            
            int mn = 0;//记录最小值
            for (int x = 1; x <= n; x++) {
                for (int y = 1; y < x; y++) {
                    mn += f[x][y];
                }
            }
            res = min(res, mn);
        }
    }
    
    cout << res << endl;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int T = 1;
// cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-11-21 00:41  wwjjw  阅读(46)  评论(0)    收藏  举报