CodeForces - 25C Roads in Berland (Floyd + 插点)

分析:对于每次新建的一条路径,假设该路径对原图的最短路没有影响,则继承上次的答案,否则先更新(u,v)的最短路,再对点对(u,v)分别插点更新全图,再计算结果

 

#include
using namespace std;
const int N = 3e2 + 5;
int G[N][N];
void floyd(int n) {
    int i, j, k;
    for(k = 1; k <= n; k += 1) {
        for(i = 1; i <= n; i += 1) {
            for(j = 1; j <= n; j += 1)
                G[i][j] = min(G[i][j], G[i][k] + G[k][j]);
        }
    }
}
void update(int k, int n) {
    int i, j;
    for(i = 1; i <= n; i += 1) {
        for(j = 1; j <= n; j += 1)
            G[i][j] = min(G[i][j], G[i][k] + G[k][j]);
    }
}
long long getvalue(int n) {
    int i, j;
    long long res = 0;
    for(i = 1; i <= n; i += 1) {
        for(j = i + 1; j <= n; j += 1)
            res += G[i][j];
    }
    return res;
}
long long pre,query[N];
int main() {
    int n, k, i, j;
    scanf("%d", &n);
    for(i = 1; i <= n; i += 1) {
        for(j = 1; j <= n; j += 1)
            scanf("%d", &G[i][j]);
    }
    floyd(n);
    pre=getvalue(n);
    scanf("%d", &k);
    int u, v, c;
    for(i = 1; i <= k; i += 1) {
        scanf("%d%d%d", &u, &v, &c);
        if(G[u][v] > c) {
            G[u][v] = G[v][u] = c;
            update(u, n);
            update(v, n);
            pre = getvalue(n);
        }
        query[i] = pre;
    }
    for(i = 1; i <= k; i += 1)
        printf("%lld%c", query[i], i < k ? ' ' : '\n');
    return 0;
}

 

你可能感兴趣的:(数论)