hdu2807The Shortest Path floyd

//对于矩阵A,B,C A*B = C
//那么A,C之间有一条路
//找出A,C的最短路
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std ;
const int maxn = 110 ;
const int inf = 0x3f3f3f3f ;
int A[maxn][maxn][maxn] ;
int map[maxn][maxn] ;
int tmp[maxn][maxn] ;
int n , m ;
bool judge(int a[maxn][maxn]  , int b[maxn][maxn])
{
    for(int i = 1;i <= m;i++)
    for(int j = 1;j <= m;j++)
    if(a[i][j] != b[i][j])
    return false ;
    return true ;
}
void floyd()
{
    for(int k = 1;k <= n;k++)
      for(int i = 1;i <= n;i++)
        for(int j = 1;j <= n;j++)
        if(map[i][j] > map[i][k] + map[k][j])
        map[i][j] = map[i][k] + map[k][j] ;
}
int main()
{
   // freopen("in.txt" ,"r" , stdin) ;
    while(scanf("%d%d" , &n , &m) && (n+m))
    {
        for(int i = 1;i <= n;i++)
        for(int j = 1;j <= m;j++)
        for(int k = 1;k <= m;k++)
        scanf("%d" , &A[i][j][k]) ;

        for(int i = 1;i <= n;i++)
        for(int j = 1;j <= n;j++)
        map[i][j] = i ==  j ? 0 : inf ;

        for(int i = 1;i <= n;i++)
        for(int j = 1;j <= n;j++)
        {
            if(i == j)continue ;
            for(int r = 1;r <= m;r++)
            for(int c = 1;c <= m;c++)
            {
                int sum = 0 ;
                for(int k = 1;k <= m;k++)
                sum += A[i][r][k]*A[j][k][c] ;
                tmp[r][c] = sum ;
            }
            for(int k = 1;k <= n;k++)
            if(k == i || k == j)continue ;
            else if(judge(A[k] , tmp))map[i][k] = 1 ;

        }

        floyd() ;
        int k ;
        scanf("%d" , &k) ;
        while(k--)
        {
            int a , b ;
            scanf("%d %d" , &a , &b) ;
            if(map[a][b] != inf)
            printf("%d\n" , map[a][b]) ;
            else puts("Sorry") ;
        }
    }
}

你可能感兴趣的:(floyd)