最短路径丶万

#include <stdio.h>
#include<cstring>
#include<iostream>
using namespace std;
struct Gh
{
    int n;//顶点数
    int m;//边数
    int weight;
    int e[10][10];
};
int main()
{
    Gh G;
    char ch[10];
    string path[100][100];
    int k,i,j,t1,t2,t3;
    cout<<"请输入顶点数和边数:";
    cin>>G.n>>G.m;
    cout<<"输入每条边:";
    for(i=0;i<G.n;i++)
        cin>>ch[i];
    //初始化
    for(i=0;i<G.n;i++)
        for(j=0;j<G.n;j++)
        {
            if(i==j) G.e[i][j]=0;
            else G.e[i][j]=999999;
        }


    //读入边
    cout<<"请输入每条边的起始点和终点和权值共"<<G.m<<"条边:"<<endl;
    for(i=0;i<G.m;i++)
    {
        cin>>t1>>t2>>t3;
        G.e[t1][t2]=t3;
    }
    for(i=0;i<G.n;i++)
        for(j=0;j<G.n;j++)
    {
        if(G.e[i][j]!=999999)
            path[i][j]=ch[i]+ch[j];
        else
            path[i][j]=" ";
    }
     cout<<endl;
    //Floyd-Warshall算法核心语句
    for(k=0;k<G.n;k++)
        for(i=0;i<G.n;i++)
            for(j=0;j<G.n;j++)
                if(G.e[i][j]>G.e[i][k]+G.e[k][j] )
                    {
                        G.e[i][j]=G.e[i][k]+G.e[k][j];
                        path[i][j]=path[i][k]+path[k][j].substr(1);
                    }


    //输出最终的结果
    for(i=0;i<G.n;i++)
    {
     for(j=0;j<G.n;j++)
        {
            if(G.e[i][j]==999999)
                cout<<"∞"<<" ";
            else
                cout<<G.e[i][j]<<"  ";
        }
        cout<<endl;
    }
    for(i=0;i<G.n;i++)
    {
     for(j=0;j<G.n;j++)
        {
                cout<<path[i][j]<<"  ";
        }
        cout<<endl;
    }


    return 0;
}
/*0 1 13
0 3 4
1 0 13
1 2 15
1 4 5
2 3 12
3 0 4
3 2 12
4 2 6
4 3 3*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值