牛客_BFC_I_Wanna_Go_Home_C++

该博客介绍了如何使用BFS(宽度优先搜索)和优先队列解决一个关于在限定条件下找到最短路径的问题。题目背景是国家内战,商人M需要从1号城市到2号城市,途中只能改变一次支持的领导人。博客详细讲解了如何构建邻接矩阵,以及如何利用BFS和优先队列找到满足条件的最短路径。
摘要由CSDN通过智能技术生成

牛客_BFC_I_Wanna_Go_Home_C++

题目描述

​ The country is facing a terrible civil war----cities in the country are divided into two parts supporting different leaders. As a merchant, Mr. M does not pay attention to politics but he actually knows the severe situation, and your task is to help him reach home as soon as possible. “For the sake of safety,”, said Mr.M, “your route should contain at most 1 road which connects two cities of different camp.” Would you please tell Mr. M at least how long will it take to reach his sweet home?

大意是M先生(后文均以M代替之)现需要从 1 号城市 到 2 号城市;

地图上含至少两个城市,从一个城市到另一个城市存在多条不同长度的路径,路径为双向,

现有两个领导人 1 和 2;

1号城市支持领导人1,2号城市支持领导人2;

其余城市各有支持的领导人,但是仅为1或2

M需要在地图上从1城去到2城,且过程中只能变换支持的领导人一次,即从支持1到支持2

求最短路径

输入描述

The input contains multiple test cases.
The first line of each case is an integer N (2<=N<=600), representing the number of cities in the country.
The second line contains one integer M (0<=M<=10000), which is the number of roads.
The following M lines are the information of the roads. Each line contains three integers A, B and T, which means the road between city A and city B will cost time T. T is in the range of [1,500].
Next part contains N integers, which are either 1 or 2. The i-th integer shows the supporting leader of city i.
To simplify the problem, we assume that Mr. M starts from city 1 and his target is city 2. City 1 always supports leader 1 while city 2 is at the same side of leader 2.
Note that all roads are bidirectional and there is at most 1 road between two cities.
Input is ended with a case of N=0.

第一行为 地图上的 城市数目N

第二行为 地图上的 道路数目M

后M行为 道路的信息,城市 A 和 B 以及 长度 T ∈ [1,500]

后N行仅为1或2,指第 i 个城市支持的领导人

输入以 N = 0 结束

输出描述

For each test case, output one integer representing the minimum time to reach home.
If it is impossible to reach home according to Mr. M’s demands, output -1 instead.

输出最短路径,无则 -1

示例

输入:

2
1
1 2 100
1 2
3
3
1 2 100
1 3 40
2 3 50
1 2 1
5
5
3 1 200
5 3 150
2 5 160
4 3 170
4 2 170
1 2 2 2 1
0

输出:

100
90
540

心路历程

此题我选用 领接矩阵 和 BFC + 优先队列 解答:

邻接矩阵:

5
5
3 1 200
5 3 150
2 5 160
4 3 170
4 2 170
1 2 2 2 1 // 领导人

将如上输入转化为邻接矩阵:

注意 1 3 200 和 3 1 200 本质上是同一个数据

int numberOfRoad;
cin >> numberOfRoad;
        
// 初始化 领接矩阵
vector<vector<int>> roadMap;
for(int i = 0;i < numberOfCity;i++) {
   
	vector<int> temp(numberOfCity,INT_MAX);
	roadMap.push_back(temp);
}
        
for(int i = 0;i < numberOfRoad;i++) {
   
	int row;
	int column;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值