洛谷P1119 灾后重建 - Floyed

对floyed的过程仔细分析,发现其实是一个以“除去起点和终点,中间经过的点编号的最大值”为阶段的DP
由于这道题保证了从0~N-1城市是依次修建完成的,可以说在i城市修建完成之前,i后面的城市都不可经过,又因为询问的t是递增的,所以每次的询问可看作对不同阶段的最短路查询,按照阶段来floyed就可以了,注意判-1

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 210;
const int MAXM = 20000 * 2;
const int INF = 1e7*2;
int n,m,ans,query,dis[MAXN],t[MAXN],gra[MAXN][MAXN],tot,now;
int main() {
    cin >> n >> m;
    for(int i=1; i<=n; i++) {
        cin >> t[i];
    }
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++) {
            if(i == j) {
                gra[i][j] = 0;
                continue;
            }
            gra[i][j] = INF;
        }
    }
    for(int i=1; i<=m; i++) {
        int x,y,w;
        cin >> x >> y >> w;
        gra[x+1][y+1] = gra[y+1][x+1] = w;
    }
    now = t[1];
    int tem = 1;
    cin >> query;
    for(int i=1; i<=query; i++) {
        int x,y,tim;
        cin >> x >> y >> tim;
        while(tim >= now && tem<=n) {
            for(int j=1; j<=n; j++) {
                for(int k=1; k<=n; k++) {
                    gra[j][k] = min(gra[j][k], gra[j][tem] + gra[tem][k]);
                }
            }
            now = t[++tem];
        }
        if(t[max(x,y)+1] > tim || gra[x+1][y+1] == INF) {
            cout << "-1" << endl;
            continue;
        }
        cout << gra[x+1][y+1] << endl;
    }
      return 0;
}

猜你喜欢

转载自blog.csdn.net/Fantasy_World/article/details/81253791
今日推荐