[Programming question] Niu Niu looking for a job

topic:

In order to find a job that he is satisfied with, Niuniu collected the difficulty and pay of each job. The standard for Niuniu to choose a job is to choose the job with the highest pay when the difficulty does not exceed its own ability value. After Niu Niu selected his job, Niu Niu's friends came to Niu Niu to help him choose a job, and Niu Niu still used his own standards to help his friends. Niuniu has too many friends, so he had to give you this task. 

Enter description:

Each input contains a test case.
The first line of each test case contains two positive integers, representing the number of jobs N (N<=100000) and the number of small partners M (M<=100000).
The next N lines each contain two positive integers representing the difficulty Di (Di<=1000000000) and the reward Pi (Pi<=1000000000) of the job, respectively.
The next line contains M positive integers, which represent the ability values ​​Ai of the M small partners (Ai<=1000000000).
Guaranteed that no two jobs pay the same.

Output description:

For each buddy, output a positive integer on a separate line to represent the highest reward he can get. A job can be selected by multiple people.

Input example 1:

3 3
1 100
10 1000
1000000000 1001
9 10 1000000000

Output example 1:

100
1000
1001

【solve】

① Sort the input work difficulty and remuneration according to the difficulty of the work from small to large, then traverse the array, update to the current work difficulty, and get the maximum remuneration, save the array after the update is completed in the TreeMap, and then you can Find the difficulty (<=) of the ability closest to the input in the map, and get the most reward based on the difficulty.

import java.util. *;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[][] arr = new int[n][2];
        for (int i = 0;i < n;i ++){
            arr[i][0] = sc.nextInt();
            arr[i][1] = sc.nextInt();
        }
        Arrays.sort(arr,((o1, o2) -> o1[0] - o2[0]));
        for (int i = 1;i < n;i ++){
            arr[i][1] = Math.max(arr[i][1],arr[i - 1][1]);
        }
        TreeMap<Integer,Integer> map = new TreeMap<>();
        for (int i = 0;i < n;i ++){
            map.put(arr[i][0],arr[i][1]);
        }
        for (int i = 0;i < m;i ++){
            int ability = sc.nextInt();
            Integer index = map.floorKey(ability);
            if (index != null){
                System.out.println(map.get(index));
            }else {
                System.out.println(0);
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324432320&siteId=291194637