平安科技两道编程题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012017783/article/details/83005192

一、求树的高度

import java.util.ArrayList;
import java.util.Scanner;
 
public class Main{
    public static void main(String[] args) {
        Scanner in  = new Scanner(System.in);
        ArrayList<String>arr=new ArrayList<>();
        while(in.hasNext()) {
        	arr.add(in.nextLine());
        }
        int n = arr.size()+1;
        if(n<3){
            System.out.println(n);
        }
        else{
            int[] height = new int [n];
            int[] binary = new int[n];
            height[0] = 1;
            int max = 0;
            for(int i = 0;i<n-1;i++){
	            String[]str=arr.get(i).split("\\s+");
                int parent = Integer.valueOf(str[0]);
                int child = Integer.valueOf(str[1]);
                binary[parent] += 1;
                if(binary[parent] < 3){
                    height[child] = height[parent]+1;
                }
                max = Math.max(max, height[child]);
            }
            System.out.println(max);
        }
    }
}

二、平均成绩降序输出

import java.util.*;
import java.util.Map.Entry;
 
public class Main {
 
    public static void main(String[] args) {
     
        Scanner sc = new Scanner(System.in);
        HashMap<String,Integer>map=new HashMap<>();
        while(sc.hasNext()) {
        	String[] str=sc.nextLine().split("\\s+");
        	double sum=0;
        	for(int i=1;i!=str.length;i++) {
        		
        		sum+=Integer.valueOf(str[i]);
        	}
        	map.put(str[0], (int) Math.round(sum/(str.length-1)));
        	
        }
    	List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			//降序排序
			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				//return o1.getValue().compareTo(o2.getValue());
				return o2.getValue().compareTo(o1.getValue());
			}
		});
 
		for (Map.Entry<String, Integer> mapping : list) {
			System.out.println(mapping.getKey() + " " + mapping.getValue());
		}

        
    }
}


 
 

		

	

猜你喜欢

转载自blog.csdn.net/u012017783/article/details/83005192