【Floyed】最短路上的统计

L i n k Link Link

SSL 1500

D e s c r i p t i o n Description Description

一个无向图上,没有自环,所有边的权值均为1,对于一个点对(a,b),我们要把所有a与b之间所有最短路上的点的总个数输出。

I n p u t Input Input

第一行n,m,表示n个点,m条边
接下来m行,每行两个数a,b,表示a,b之间有条边
在下来一个数p,表示问题的个数
接下来p行,每行两个数a,b,表示询问a,b

O u t p u t Output Output

对于每个询问,输出一个数c,表示a,b之间最短路上点的总个数

S a m p l e Sample Sample I n p u t Input Input

5 6
1 2
1 3
2 3
2 4
3 5
4 5
3
2 5
5 1
2 4

S a m p l e Sample Sample O u t p u t Output Output

4
3
2

E x p l a i n Explain Explain

n<=100,p<=5000

T r a i n Train Train o f of of T h o u g h t Thought Thought

首先用 F l o y e d Floyed Floyed求出最短路,接着在看有多少条路径值与最短路的值相等

C o d e Code Code

#include
#include
#include
using namespace std;
int n,m,a[101][101],ans[101][101];
int x,y,p;
int main()
{
	memset(a,127/3,sizeof(a));
	scanf("%d%d",&n,&m);
	for (int i=1; i<=n; i++) a[i][i]=0;
	for (int i=1; i<=m; ++i)
	{
		scanf("%d%d",&x,&y);
		a[x][y]=a[y][x]=1;
	}	
	for (int k=1; k<=n; ++k)
	 for (int i=1; i<=n; ++i)
	  for (int j=1; j<=n; ++j)
	   a[i][j]=min(a[i][j],a[i][k]+a[k][j]);//求最短路
	for (int k=1; k<=n; ++k)
	 for (int i=1; i<=n; ++i)
	  for (int j=1; j<=n; ++j)
	   if(a[i][k]+a[k][j]==a[i][j]) ans[i][j]++;//统计有多少条路径
	scanf("%d",&p);
	for (int i=1; i<=p; ++i)
	 {
	 	scanf("%d%d",&x,&y);
	 	printf("%d\n",ans[x][y]);
	 }
	return 0;
}

你可能感兴趣的:(Floyed,图论,最短路,图论,最短路,Floyed)