洛谷P1119 灾后重建

floyd的变形,本质是求从i号顶点到j号顶点只经过前k号点的最短路程。

#include<bits/stdc++.h>
using namespace std;

const int N = 300,INF = 0x3f3f3f3f;

int n,m,qn;
int g[N][N],t[N];

void update(int k){
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			if(g[i][j]>g[i][k]+g[k][j])
				g[i][j]=g[i][k]+g[k][j];
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int x,y,z;
    int cnt=0;
    cin>>n>>m;
    for(int i=0;i<n;i++){
		cin>>t[i];
    }
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            g[i][j]=INF;
    //for(int i=0;i<n;i++) g[i][i]=0;
    for(int i=0;i<m;i++){
        cin>>x>>y>>z;
        g[x][y]=z;
        g[y][x]=z;
    }
    cin>>qn;
    int now=0;
    for(int i=0;i<qn;i++){
        cin>>x>>y>>z;
        while(t[now]<=z && now<n){
        	update(now);
        	now++;
		}
		if(t[x]>z || t[y]>z || g[x][y] == INF) cout<<"-1"<<endl;
		else cout<<g[x][y]<<endl;
    }
    return 0;
}
posted @ 2022-05-05 22:30  xhy666  阅读(37)  评论(0)    收藏  举报