题目

输入
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;
}
}
2576

被折叠的 条评论
为什么被折叠?



