最短路上的统计(4.8 jzoj第一题)

来源:互联网 发布:java中迭代器的使用 编辑:程序博客网 时间:2024/04/29 01:01

题目:

Description

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

Input

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

Output

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

Sample Input

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

Sample Output

4
3
2

作者思路:用floyd求出距离,在用一个判断输出

代码:

var a:array[0..101,0..101] of longint;    x,y,n,m,i,j,k,p,ans:longint;begin  read(n,m); // fillchar(a,sizeof(a),maxlongint); for i:=1 to n do for j:=1 to n do if i<>j then a[i,j]:=maxlongint;  for i:=1 to m do  begin    read(x,y);    a[x,y]:=1; a[y,x]:=1; //f[x,y]:=1; f[y,x]:=1;  end;  for k:=1 to n do  for i:=1 to n do    for j:=1 to n do      if (a[i,k]<>maxlongint)and(a[k,j]<>maxlongint) then      if a[i,j]>a[k,j]+a[i,k] then begin a[i,j]:=a[k,j]+a[i,k]; end;  read(p);  for i:=1 to p do  begin    read(x,y);    //writeln(f[x,y]+1);    ans:=0;    for j:=1 to n do      if(a[x,j]<>maxlongint)and(a[j,y]<>maxlongint) then      if a[x,j]+a[j,y]=a[x,y] then inc(ans);    writeln(ans);  end;end.
1 0