時間限制:2秒ide
空間限制:65536K測試
每一個輸入包含一個測試用例。
每一個測試用例的第一行包含兩個正整數,分別表示工做的數量N(N<=100000)和小夥伴的數量M(M<=100000)。
接下來的N行每行包含兩個正整數,分別表示該項工做的難度Di(Di<=1000000000)和報酬Pi(Pi<=1000000000)。
接下來的一行包含M個正整數,分別表示M個小夥伴的能力值Ai(Ai<=1000000000)。
保證不存在兩項工做的報酬相同。
對於每一個小夥伴,在單獨的一行輸出一個正整數表示他能獲得的最高報酬。一個工做能夠被多我的選擇。
3 3 1 100 10 1000 1000000000 1001 9 10 1000000000
100 1000 1001
法一(借鑑):用map存儲工做能力和報酬的對應關係,不只存儲全部工做的,並且也存儲每一個小夥伴的工做能力和報酬(爲0),這樣在後面計算的時候不用兩層for循環,而使用一層for循環就能夠搞定,
由於不須要判斷小夥伴的能力值和工做能力值的大小關係,只須要計算,到目前的能力值爲止,所能得到的最大報酬數,有種dp的味道,用ma保存歷史最大報酬數,而後再更新到map中便可。o(nlgn)。代碼以下:
1 public class MainCorrect { 2 3 public static void main(String[] args) { 4 //劃重點!!!此題坑點:輸入中間有空行,因此用BuffferedReader會更麻煩,因此選擇用Scanner 5 Scanner sc = new Scanner(System.in); 6 int n = sc.nextInt(); 7 int m = sc.nextInt(); 8 //保存全部工做的鍵值對,即<工做能力,報酬>,並且也保存每一個小夥伴的能力值鍵值對,其報酬爲0 9 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 10 //保存全部工做的能力值以及要計算的每一個小夥伴的能力值 11 int[] ai = new int[m + n]; 12 for(int i = 0; i < n; i++) { 13 int di = sc.nextInt(); 14 ai[i] = di; 15 int pi = sc.nextInt(); 16 map.put(di, pi); 17 } 18 //保存要計算的每一個小夥伴的能力值 19 int[] bi = new int[m]; 20 for(int i = 0; i < m; i++) { 21 ai[i + n] = sc.nextInt(); 22 bi[i] = ai[i + n]; 23 if(!map.containsKey(ai[i + n])) { 24 map.put(ai[i + n], 0); 25 } 26 } 27 //對能力值進行排序 28 Arrays.sort(ai); 29 //保存到目前的能力值爲止,所能得到的最大報酬,有種dp的味道 30 int ma = 0; 31 for(int i = 0; i < m + n; i++) { 32 //每次都更新當前能力值所對應的最大報酬,因爲ma是保存的<=當前能力值所能得到的最大報酬,因此可行 33 ma = Math.max(ma, map.get(ai[i])); 34 map.put(ai[i], ma); 35 } 36 //遍歷每一個小夥伴的能力值,從map中獲取到其最大報酬(在上面的for循環中已經更新到了) 37 for(int i = 0; i < m; i++) { 38 System.out.println(map.get(bi[i])); 39 } 40 } 41 42 }
法二:兩層for循環,先排序,後逐一進行比較判斷。o(n^2)。固然超時,僅經過40%。代碼以下:this
1 public class Main { 2 3 //用一個類來記錄工做能力和報酬的對應關係,其實能夠用map實現的 4 static class Job implements Comparable<Job>{ 5 int di, pi; 6 public Job(int di, int pi) { 7 this.di = di; 8 this.pi = pi; 9 } 10 //按工做能力值進行排序 11 public int compareTo(Job job) { 12 return this.di - job.di; 13 } 14 } 15 16 public static void main(String[] args) throws IOException { 17 Scanner sc = new Scanner(System.in); 18 int n = sc.nextInt(); 19 int m = sc.nextInt(); 20 Job[] jobs = new Job[n]; 21 for(int i = 0; i < n; i++) { 22 int di = sc.nextInt(); 23 int pi = sc.nextInt(); 24 jobs[i] = new Job(di, pi); 25 } 26 //對工做能力進行排序 27 Arrays.sort(jobs); 28 int[] ai = new int[m]; 29 for(int i = 0; i < m; i++) { 30 ai[i] = sc.nextInt(); 31 } 32 //逐一計算每一個小夥伴,在其工做能力以內所能得到的最大報酬 33 for(int i = 0; i < m; i++) { 34 int j = 0; 35 int cnt = 0; 36 while(j < n && jobs[j].di <= ai[i]) { 37 if(cnt < jobs[j].pi) { 38 cnt = jobs[j].pi; 39 } 40 j++; 41 } 42 System.out.println(cnt); 43 } 44 } 45 46 }