当前位置: 代码迷 >> 综合 >> CF25C Roads in Berland
  详细解决方案

CF25C Roads in Berland

热度:42   发布时间:2023-12-02 14:33:12.0

题目:

给定一个矩阵,g[i][j]表示从点i到点j最短距离
然后,给定k次修改,如果本次修改可以使得最短距离变得更短,请输出所有最短路径的长度
2<=n<=300
1<=d i,j <=1000
k(1<=k<=300

解决:

每次只有点a和b的距离修改了,那么,我们只要更新与a和b有关的点的距离即可。

代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 310;
int n, m;
int g[N][N];
int main()
{cin >> n;for (int i = 1; i <= n; i ++ )for (int j = 1; j <= n; j ++ )scanf("%d", &g[i][j]);cin >> m;while (m -- ){int a, b, c; scanf("%d%d%d", &a, &b, &c);if (g[a][b] > c){g[a][b] = g[b][a] = c;for (int i = 1; i <= n; i ++ )for (int j = 1; j <= n; j ++ )if (i != j){g[i][j] = g[j][i] = min(g[i][j], g[i][a] + g[a][j]); // 只有a和b需要更新,其他的点都没有更新g[i][j] = g[j][i] = min(g[i][j], g[i][b] + g[b][j]);}}long long sum = 0;for (int i = 1; i <= n; i ++ )for (int j = 1; j < i; j ++ )sum += g[i][j];printf("%lld\n", sum);}return 0;
}