P6464 [传智杯 #2 决赛] 传送门

P6464 [传智杯 #2 决赛] 传送门_第1张图片 

输入输出样例

输入 #1

4 5
1 2 3
1 3 6
2 3 4
2 4 7
3 4 2

输出 #1

14

 

#include 
#define bug printf("************\n");
#define fuck(x) cout << #x << " -> " << x << endl
#define endl '\n'
#define int long long
using namespace std;
constexpr int N = 1e6 + 10, inf = 0x3f3f3f3f;
int minn = inf;
int n, m;
int a, b, c;
int g[120][120];
int change[120][120];
void floyd(int i, int j)
{
    for (int k1 = 1; k1 <= n; k1++)//i为中转点;
        for (int k2 = 1; k2 <= n; k2++)
            change[k1][k2] = min(change[k1][k2], change[k1][i] + change[i][k2]);
    for (int k1 = 1; k1 <= n; k1++)//j为中转点;
        for (int k2 = 1; k2 <= n; k2++)
            change[k1][k2] = min(change[k1][k2], change[k1][j] + change[j][k2]);
    // 做floyd

    //i与j连接的边改变,则以i为j为中转点的点需要进行动态规划
}
void realfloyd()
{
    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 getsum()
{
    int sum = 0;
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            // if (i == j)
            // {
            //     continue;
            // }
            if (change[i][j] == inf)
            {
                continue;
            }
            sum += change[i][j];
        }
    }
    return sum;
}

void solve()
{
    memset(g, 0x3f, sizeof g);
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> a >> b >> c;
        g[a][b] = g[b][a] = c;
    }
    // 枚举
    realfloyd();
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (i == j)
            {
                continue;
            }
            memcpy(change, g, sizeof g);
            change[i][j] = change[j][i] = 0;
            floyd(i, j);
            // fuck(g[1][3]);
            int temp = getsum();
            minn = min(minn, temp);
        }
    }
    cout << minn << endl;
}

signed main()
{
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    int T = 1;

    while (T--)
    {
        solve();
    }

    return 0;
}

你可能感兴趣的:(ou_fan的学习记录,c++,算法,动态规划)