码迷,mamicode.com
首页 > 其他好文 > 详细

最短送餐路程计算, 美团笔试题2020

时间:2020-07-12 20:23:12      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:++   finish   amp   +=   util   mat   ||   int()   value   

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

标签:++   finish   amp   +=   util   mat   ||   int()   value   

原文地址:https://www.cnblogs.com/lixyuan/p/13289589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!