关键字:最短路径,有条件限制
题目:
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?
输入描述:
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.
输出描述:
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
思路:
只要把不在一个阵营的边设置成有向边即可:leader1->deader2通,leader2->leader1不通
具体见代码。
代码:
#include <iostream>
#include <fstream>
using namespace std;
#define INF 9999999
const int maxn = 610;
const int maxm = 10010;
int n;
int G[maxn][maxn];
int leader[maxn];
void floyd(){
for(int k = 1; k <= n; ++k){
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if(G[i][j] > G[i][k] + G[k][j]){
G[i][j] = G[i][k] + G[k][j];
}
}
}
}
}
int main(){
int m, a, b, c;
// freopen("a.txt", "r", stdin);
while(cin >> n >> m && n != 0){
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if(i == j) G[i][j] = 0;
G[i][j] = INF;
}
}
for(int i = 0; i < m; ++i){
cin >> a >> b >> c;
if(G[a][b] > c){
G[a][b] = G[b][a] = c; //20%的未通过案例来自这句
}
}
for(int i = 1; i <= n; ++i){
cin >> leader[i];
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
//只要把不在一个阵营的边设置成有向边即可:leader1->deader2通,leader2->leader1不通
if(leader[i] == 2 && leader[j] == 1){
G[i][j] = INF;
}
}
}
floyd();
if(G[1][2] == INF) cout << "-1" << endl;
else cout << G[1][2] << endl;
}
return 0;
}

这是一道关于最短路径的编程题,要求在最多经过一条连接不同阵营城市的路线的情况下,帮助商人Mr. M从城市1到城市2。输入包含城市数量、道路信息和城市阵营,输出是最短时间或-1表示无法按要求到达。可以通过将不同阵营之间的边设置为有向边来简化问题。

491

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



