COGS 2. 旅行计划

★☆   输入文件:djs.in   输出文件:djs.out   简单对比
时间限制:3 s   内存限制:128 MB

过暑假了,阿杜准备出行旅游,他已经查到了某些城市的两两之间的距离及可行路线(可行路线有方向),如下图所示。请你编程计算从阿杜所住城市到其它城市的最短路径以帮助阿杜制定旅行计划。

【输入格式】

输入由若干行组成,第一行有三个整数,n1n100m1mn2v1mn;城市数,m城市间道路数,v是阿杜所住城市。第2m+1行是每条路的信息,每行三个整数,为道路的起点、终点和两城市间距离。(城市从0开始编号)

【输出格式】

n组(按城市编号由小至大),每组三行

第一行:城市编号及一个冒号

第二行:path及一个冒号,后面是最短路径节点编号序列(编号间用一个空格隔开)

第三行:cost及一个冒号,后面是一个整数,表示路径距离

如果没有通路则输出 no

【输入样例】

6 8 0
0 2 10
0 4 30
0 5 100
1 2 5
2 3 50
3 5 10
4 3 20
4 5 60

【输出样例】

0:
no
1:
no
2:
path:0 2
cost:10
3:
path:0 4 3
cost:50
4:
path:0 4
cost:30
5:
path:0 4 3 5
cost:60

floyd
屠龙宝刀点击就送
#include <cstring>
#include <cstdio>

#define Max 100
#define min(a,b) a>b?b:a

void qr(int &x)
{
    x=0;bool f;
    char ch=getchar();
    while(ch>'9'||ch<'0')
    {
        if(ch=='-') f=1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=x*10+(int)ch-48;
        ch=getchar();
    }
    f?(~x+1):x;
}
int tx[Max*2][Max*2],cnt=0,path[Max*2][Max*2],n,m,v;
void floyd()
{
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<n;++j)
        {
            for(int k=0;k<n;++k)
            {
                if(tx[j][k]>tx[j][i]+tx[i][k])
                {
                    tx[j][k]=tx[j][i]+tx[i][k];
                    path[j][k]=path[j][i];
                }
            }
        }
    }
}
int main()
{
    freopen("djs.in","r",stdin);
    freopen("djs.out","w",stdout); 
    scanf("%d%d%d",&n,&m,&v);
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
            path[i][j]=j,tx[i][j]=1e8;
    for(int x,y,z;m--;)
    {
        scanf("%d%d%d",&x,&y,&z);
        tx[x][y]=min(tx[x][y],z);
     }
    floyd();
    for(int i=0;i<n;++i)
    {
        printf("%d:\n",i);int tmp=v;
        if(i==v)
        {
            printf("no\n");
            continue;
        }
        else if(tx[v][i]==1e8)
        {
            printf("no\n");
            continue;
        }
        else 
        {
            printf("path:");
            while(tmp!=i)
            {
                printf("%d ",tmp);
                tmp=path[tmp][i];
            }
            printf("%d\ncost:%d\n",i,tx[v][i]);
        }
    }
    return 0;
}

 

posted @ 2017-03-18 15:43  杀猪状元  阅读(162)  评论(0编辑  收藏  举报