Codingame一道中等难度的题目
要求
Knight会获得以当前位置为坐标中心的导航指示(U, UR, R, DR, D, DL, L or UL)
- U -> Up
- D -> Down
- R -> Right
- L -> Left
根据指示到达目标点
思路
应用了对分查找,大量减少猜测范围。
代码
import java.util.*;
import java.io.*;
import java.math.*;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Player {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int W = in.nextInt(); // width of the building.
int H = in.nextInt(); // height of the building.
int N = in.nextInt(); // maximum number of turns before game over.
int X0 = in.nextInt();
int Y0 = in.nextInt();
int startX = 0,endX = W-1,middleX = -1;
int startY = 0,endY = H-1,middleY = -1;
System.err.println(W+" "+H);
// game loop
while (true) {
String bombDir = in.next(); // the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)
if(bombDir.contains("U")){
if(middleY == -1)
endY = Y0 - 1;
else
endY = middleY-1;
}
else if(bombDir.contains("D")){
if(middleY == -1)
startY = Y0 + 1;
else
startY = middleY+1;
}
if(bombDir.contains("R")){
if(middleX == -1)
startX = X0 + 1;
else
startX = middleX+1;
}
else if(bombDir.contains("L")){
if(middleX == -1)
endX = X0 - 1;
else
endX = middleX-1;
}
middleX = getMiddle(startX,endX);
middleY = getMiddle(startY,endY);
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
// the location of the next window Batman should jump to.
System.out.println(middleX+" "+middleY);
}
}
public static int getMiddle(int start,int end){
return (start+end)/2;
}
}
后续修正
突然发现之前没有提交,在正式提交时发现塔的那一关未达成,于是在第一次确定搜索范围时,去除了原先站的位置。于是达成100%.