UVA 627 (Floyd最短路)

根据题目描述,很显然就是Floyd的思想,所以直接上来怼就行啦。。
熟悉Floyd思想,不明白的可以看这里Floyd-Warshall
AC代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define MAXNL 0x3fffffff
#define MAXN 0x3f3f3f3f
using namespace std;

//#define debug

int n;

int mmp[305][305];

void init(){
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i==j) mmp[i][j]=0;
            else mmp[i][j]=MAXN;
        }
    }
}

void Floyd()
{
    for(int k=1;k<=n;k++){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(mmp[i][j]>mmp[i][k]+mmp[k][j]){
                    mmp[i][j]=mmp[i][k]+mmp[k][j];
                }
            }
        }
    }
}

void solve(int x,int y)
{
    printf("%d",x);
    while(mmp[x][y]!=1){
        for(int i=1;i<=n;i++){
            if(mmp[x][i]==1&&mmp[x][y]==mmp[x][i]+mmp[i][y]){
                printf(" %d",i);
                x=i;
                break;
            }
        }
    }
    printf(" %d\n",y);
}

int main()
{
    #ifdef debug
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // debug

    char str[1025];
    while(~scanf("%d",&n)){
        init();
        for(int i=0;i<n;i++){
            scanf(" %s",str);
            int a=-1,b=0;
            for(int j=0,len=strlen(str);j<=len;j++){
                if(a==-1&&str[j]!='-'){
                    b=b*10+str[j]-'0';
                }
                else if(a==-1&&str[j]=='-'){
                    a=b;b=0;
                }
                else if(a!=-1&&isdigit(str[j])){
                    b=b*10+str[j]-'0';
                }
                else if(str[j]==','||str[j]=='\0'){
                    mmp[a][b]=1;
                    b=0;
                }
            }
        }
        Floyd();
        int a,b,m;
        scanf("%d",&m);
        puts("-----");
        while(m--){
            scanf("%d%d",&a,&b);
            if(mmp[a][b]==MAXN) printf("connection impossible\n");
            else solve(a,b);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/80714408
627