存在N个城市:第i和i+1个之间有路径(i,i+1),第一个和第N个之间有路径(0,N-1);其中k个城市特殊,与其它城市都有唯一直接路径;每个城市具备权重r,路径(x,y)的值定义为r(x)*r(y)。问:所有路径值之和?
//JavaScript(浏览器页面按F12输入代码即可)
//arrCity:[city1[权重,特殊1],city2[权重,非特殊0],...cityN[权重,特殊1]]
var arrCity = [[6, 1], [4, 0], [1, 1], [4, 0], [4, 0], [1, 1]];
var sum = RoadSum(arrCity);
console.log(sum);
//求和
function RoadSum(Cities){
let arrRoad = Road(Cities);
let sum = 0;
for(let i = 0; i < arrRoad.length; i++){
sum += Cities[arrRoad[i][0]][0] * Cities[arrRoad[i][1]][0];
}
return sum;
}
//路径
function Road(Cities){
//N>2
let N = Cities.length;
let arrRoad = new Array();
for(let i = 0; i < N; i++){
if(i + 1 == N){
arrRoad[arrRoad.length] = [0, i];
}
else{
arrRoad[arrRoad.length] = [i, i + 1];
}
if(Cities[i][1] == 1){
for(let j = 0; j < N; j++){
if(j < i - 1 && i - j != N - 1 && Cities[j][1] == 0){
arrRoad[arrRoad.length] = [j, i];
}
else if(j > i + 1 && j - i != N - 1){
arrRoad[arrRoad.length] = [i, j];
}
}
}
}
return arrRoad;
}
来源:CSDN
作者:Long_Long_Time_Ago_
链接:https://blog.csdn.net/m0_46193048/article/details/104633739