Floyd

9.Floyd


Floyd的求最短路

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210518203939464.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MzAzNzM3OQ==,size_16,color_FFFFFF,t_70)

输入样例:

3 3 2
1 2 1
2 3 2
1 3 1
2 1
1 3

输出样例:

impossible
1

模板:

//多源汇最短路
// Floyd 求最短路
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 210,INF = 1e9;

int n,m,Q;
int d[N][N];  //矩阵 

void floyd(){
	for(int k=1;k<=n;k++)
	    for(int i=1;i<=n;i++)
	        for(int j=1;j<=n;j++)
	            d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}

int main(){
	scanf("%d%d%d",&n,&m,&Q);
	
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			if(i==j) d[i][j]=0;   //初始化处理自环 
			else d[i][j]=INF;
		
	while(m--){
		int a,b,w;
		scanf("%d%d%d",&a,&b,&w);
		
		d[a][b]=min(d[a][b],w);
	}
	
	floyd();
	
	while(Q--){
		int a,b;
		scanf("%d%d",&a,&b);
		
		if(d[a][b]>INF/2) puts("impossible");
		else printf("%d\n",d[a][b]);
	}
	
	return 0;
}

 

posted @ 2022-03-22 01:07  panse·  阅读(41)  评论(0)    收藏  举报