最短送餐路程计算, 美团笔试题2020
Posted lixyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最短送餐路程计算, 美团笔试题2020相关的知识,希望对你有一定的参考价值。
import java.util.*;
public class Main {
static int dijkstra(int[][] g, int n, int target, int k, int value){
boolean[] finished = new boolean[n];
int[] distance = new int[n];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[0] = k == 0 ? value : 0;
if(k != 0) {
for(int i=0; i < n; i++)
if(i != k && g[k][i] != -1) {
g[i][k] = g[k][i] += value;
}
}
for(int i=0; i < n; i++) {
int t = -1;
for(int j=0; j < n; j++) {
if(finished[j]==false &&(t == -1 || distance[t] > distance[j])) {
t = j;
}
}
finished[t] = true;
for(int j=0; j < n; j++) {
if(g[t][j] != -1) {
distance[j] = Math.min(distance[j], distance[t]+g[t][j]);
}
}
}
return distance[target];
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int target = sc.nextInt();
int k = sc.nextInt(), value=sc.nextInt();
int n = 6;
int[][] g = new int[n][n];
for(int i=0; i < n; i++){
Arrays.fill(g[i], -1);
g[i][i] = 0;
}
g[0][1] = 1; g[0][2] = 2; g[0][3] = 7;
g[1][0] = 1; g[1][2] = 2; g[1][4] = 5; g[1][5] = 4;
g[2][0] = 2; g[2][1] = 2; g[2][4] = 4; g[2][3] = 4;
g[3][0] = 7; g[3][2] = 4; g[3][4] = 6;
g[4][1] = 5; g[4][2] = 4; g[4][3] = 6; g[4][5] = 3;
g[5][1]=4; g[5][4] = 3;
System.out.println(dijkstra(g, n, target, k, value));
}
}
以上是关于最短送餐路程计算, 美团笔试题2020的主要内容,如果未能解决你的问题,请参考以下文章