打赏

完美世界:笔试题(最小漂流船只数累计,主城之间的最小距离迪杰斯特拉)

第一题

第一道题要计算的是最小漂流船,已知每艘船最多可以承载2人,但是重量不能超过limit,求最少需要多少船只?

第一行输入的是参与人员的体重数组,第二行输入的是漂流船承载的最大重量。求最小船只数?

 

import java.util.Arrays;
import java.util.Scanner;
public class B4 {
    public int N = 2;
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String[] weightstr = sc.nextLine().split(" ");
        int limit = sc.nextInt();
        int num = weightstr.length;
        int[] weight = new int[num];
        for (int i = 0; i < weight.length; i++) {
            weight[i] = Integer.valueOf(weightstr[i]);
        }
        int result = getShipNum(weight, num, limit);
        System.out.println(result);
    }
    
    public static int getShipNum(int[] weight,int num, int limit){
        int number = 0;
        Arrays.sort(weight);
        int i,j;
        for (i=num-1, j=0; i>=0 && j<=num-1 && j<i; i--) {
            number++;
            if(weight[i]+weight[j]<=limit){
                j++;
            }
        }
        if(j==i){
           number++; 
        }
        return number;
    }
}

第二题

第二道要计算主城之间的最小距离,应该是要用迪杰斯塔拉算法。

public class B5 {
    public static int N = 6;
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int[][] relation = new int[N][N];
        for (int i = 0; i < N; i++) {
            String[] vi = sc.nextLine().split(" ");
            for (int j = 0; j < N; j++) {
                relation[i][j] = Integer.valueOf(vi[j]);
                if(relation[i][j]==-1){
                    relation[i][j] = Integer.MAX_VALUE;
                }
            }
            
        }
        int[] shortestTime = getShortestTime(relation);
        for (int i = 1; i < N; i++) {
            System.out.println(shortestTime[i]);
        }
    }
    
    public static int[] getShortestTime(int[][] relation){
        int[] shortestTime = new int[N];
        shortestTime[0] = 0;
        int visited[] = new int[N];
        visited[0] = 1;
        for (int i = 1; i < N; i++) {
            shortestTime[i] = relation[0][i];
        }
        for (int times = 0; times < N; times++) {
            int position = 0;
            int min = Integer.MAX_VALUE;
            for (int i = 1; i < N; i++) {
                if(visited[i]==0){
                    if(min>shortestTime[i]){
                        min = Math.min(min, shortestTime[i]);
                        position = i;
                    }
                }
            }
            shortestTime[position] = min;
            visited[position]=1;
            for (int j = 1; j < N; j++) {
                int newdistance = shortestTime[position]+relation[position][j];
                if(visited[j]==0 && relation[position][j]<Integer.MAX_VALUE && newdistance<shortestTime[j]){
                    shortestTime[j] = newdistance;
                }
            }
        } 
        
        return shortestTime;
    }
}

 

posted @ 2019-08-23 20:44  海米傻傻  阅读(514)  评论(0编辑  收藏  举报