標籤:import 研究院 hashmap ace return ndt max ash 測試
題目:
天上掉餡餅
時間限制:C/C++語言 1000MS;其他語言 3000MS
記憶體限制:C/C++語言 131072KB;其他語言 655360KB
題目描述:
大家都知道“天上不會掉餡餅”這句話,但是有一天,小明在回學校的路上,天上還真掉起了餡餅。小明的人品實在有點好,這餡餅會掉在小明身邊10米的範圍內。餡餅掉在地上顯然就不能吃了,所以小明馬上拿起他的背包去接。但是,小明是個技術宅,運動方面實在不太行,每秒鐘只有在移動不超過1米的範圍內接住餡餅。這條小路的圖所示如下:
現在,我們把問題簡化一下,餡餅現在只掉在0~10這11個位置。開始時,小明站在5這個位置,因此在第一秒,他只能接到4,5,6這三個位置其中一個位置的餡餅。問小明最多能接多少個餡餅?請用Java/python/C++/C語言中的一種進行編程。
輸入
測試資料多組,每組測試資料都會給出一共掉落的餡餅數N,接下裡的N行給出每次餡餅掉落的座標X和掉落的時間T。同一秒可能掉落多個餡餅。(0<N,T<100000)
輸出
對於每個測試資料,輸出一個整數,代表小明能夠獲得最多餡餅數量。
範例輸入
6
5 1
4 1
6 1
7 2
7 2
8 3
範例輸出
Case #1:
The max number of pies is : 4
思路:時間從0開始到沒有餡餅掉落為止,遍曆所有可能的移動方式,以及每種方式所獲得的餡餅數,取最大值。
代碼(未在考試平台上測試):
1 import java.util.*; 2 3 public class Main{ 4 private void func(int endTime, int curTime, int mingPlace, Map<Integer, ArrayList<Integer>> timePlaceMap, 5 int curNum, ArrayList<Integer> numList) { 6 if (curTime > endTime) { 7 numList.add(curNum); 8 return; 9 }10 11 // 計算移動-1,0,+1步能獲得的餡餅數目12 int num_here = 0, num_before = 0, num_behind = 0;13 if (timePlaceMap.containsKey(curTime+1)) {14 ArrayList<Integer> places = timePlaceMap.get(curTime + 1);15 System.out.println("places:" + places);16 for (int place: places) {17 if (place == mingPlace) {18 num_here++;19 } else if (mingPlace > 0 && place == mingPlace - 1) {20 num_before++;21 } else if (mingPlace < 10 && place == mingPlace + 1) {22 num_behind++;23 }24 }25 }26 27 func(endTime, curTime+1, mingPlace, timePlaceMap,28 curNum + num_here, numList);// 位置不變29 if (mingPlace > 0) {30 func(endTime, curTime+1, mingPlace-1, timePlaceMap,31 curNum + num_before, numList);// 位置減132 }33 if (mingPlace < 10) {34 func(endTime, curTime+1, mingPlace+1, timePlaceMap,35 curNum + num_behind, numList);// 位置加136 }37 }38 39 public static void main(String[] args) {40 Main mainClass = new Main();41 Scanner in = new Scanner(System.in);42 while(in.hasNext()) {43 String input = in.next();44 int n = Integer.parseInt(input);45 Map<Integer, ArrayList<Integer>> timePlaceMap = new HashMap<>();46 for (int i=0; i<n; i++) {47 int place = Integer.parseInt(in.next());48 int time = Integer.parseInt(in.next());49 ArrayList<Integer> places = timePlaceMap.getOrDefault(time, new ArrayList<Integer>());50 places.add(place);51 timePlaceMap.put(time, places);52 }53 int endTime = Collections.max(timePlaceMap.keySet());54 ArrayList<Integer> numList = new ArrayList<>();55 mainClass.func(endTime, 0, 5, timePlaceMap, 0, numList);56 int maxNum = Collections.max(numList);57 System.out.println(" The max number of pies is : " + maxNum);58 }59 in.close();60 }61 }
天上掉餡餅--移動研究院2018校招筆試題