TOJ 1049 Jesse's problem (最短路 floyd)

描述

All one knows Jesse live in the city , but he must come to Xiasha twice in a week. The road is too long for him to go . But he is so much resolute that nothing can prevent him from coming . More, Jesse must take many bus to come , the length of road is different. So, Jesse think : can I take the shortest road to save time ? 

Now , the problem is puting on you , can you help him to calculate the shortest length? 

Is it easy? Just do it!

输入

The input has several test cases. The first line of each case has two number n,m (1 <= n,m <= 200 ). n means have n bus stations 1th,2th,....nth . m means have m roads. Then following next m lines ,each line have 3 integer a,b,c which means the length between a and b bus station is c(0 < c < 2000). 

Then a line with two integer s,t,means the start and end bus station.

输出

For the given start and end bus station ,output the shortest lenth between s and t in one line. 

If the road not exists,output -1.

样例输入

3 3

1 2 3

1 3 10

2 3 11

1 3

3 1

2 3 1

1 2

样例输出

10

-1

分析:

弗洛伊德算法的简单应用

代码:

#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m))
    {
        int k,a,b,c,start,end1,i,j;
        int e[205][205];
        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
                if(i==j)
                    e[i][j]=0;
                else
                    e[i][j]=0x3f3f3f3f;
        for(i=1; i<=m; i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            e[a][b]=e[b][a]=min(c,e[b][a]);//用于对输入的值进行判断,找出输入的时候的两点间的距离的最小值,无向图
        }
        scanf("%d%d",&start,&end1);

        //应用三个for循环,弗洛伊德的关键步骤
        for(k=1; k<=n; k++)
            for(i=1; i<=n; i++)
                for(j=1; j<=n; j++)
                    if(e[i][j]>e[i][k]+e[k][j])
                        e[i][j]=e[i][k]+e[k][j];
        if(e[start][end1]!=0x3f3f3f3f)
            printf("%d\n",e[start][end1]);
        else
            printf("-1\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/cmmdc/p/6767552.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值