数据结构算法——1089. 路由器

题目

在这里插入图片描述
输入
4 5
168.120.1.1 168.120.1.2 15
168.120.1.1 168.120.1.4 47
168.120.1.1 168.120.1.3 10
168.120.1.2 168.120.1.4 15
168.120.1.3 168.120.1.4 25
3
168.120.1.1 168.120.1.4
168.120.1.3 168.120.1.4
168.120.1.3 202.12.12.12

输出
30
25
-1

思路

这个数据量用floyd算法绰绰有余

由于要string索引,所以最好用map嵌套map来进行快速索引
然后需要一个set来记录所有string索引节点

记录好数据之后
利用三个for循环来进行计算即可

#include<iostream>
#include<map>
#include<set>
using namespace std;
#define INF 0x3f3f3f3f

map<string,map<string,int>> mstring;
set<string> IP;
int main()
{
    int n, m;
    cin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        string start,end;
        int cost;
        cin >> start >> end >> cost;
        mstring[start][end] = cost;
        mstring[end][start] = cost;
        IP.insert(start);
        IP.insert(end);
    }  
    for(auto i : IP)
    {
        for(auto j : IP)
        {
            if(mstring[i][j] == 0)
                mstring[i][j]= INF;
            if(i == j)
                mstring[i][j] = 0;
        }
    }
    for(auto mid : IP)
        for(auto start : IP)
            for(auto end : IP)
            {
                int temp = mstring[start][mid] + mstring[mid][end];
                if(temp < mstring[start][end])
                    mstring[start][end] = temp;
            }

    int ask;
    cin >> ask;
    for(int i = 0; i < ask; i++)
    {
        string start,end;
        cin >> start >> end;
        if(mstring[start][end] != INF && mstring[start][end] != 0)
            cout << mstring[start][end] << endl;
        else
            cout << -1 << endl;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值