SRM289Div2,300

この記事は約5分で読めます。

An object is placed in the xy-plane at coordinates (x,y), where x > 0 and y> 0. The object begins falling straight down toward the x-axis at a speed of one unit per second. Along the way, it may encounter some obstacles. Each obstacle is a horizontal line segment, and the object hits an obstacle when their y-coordinates are equal and the object’s x-coordinate is between the x-coordinates of the obstacle’s endpoints (inclusive). Each time the object hits an obstacle, it will be delayed 5 seconds. During this delay, the object will travel to the right endpoint of the obstacle (the one with the greater x-coordinate). The object will then continue to fall straight down from that point.

You are given the object’s initial position (x,y) and a String[] describing the obstacles. Return the number of seconds it will take for the object to finally reach the x-axis. Each element of obstacles is formatted “y x1 x2” (quotes for clarity only), where y is the y-coordinate of an obstacle, and x1 and x2 are the left and right x-coordinates of that obstacle’s endpoints respectively.

[java]

import java.util.Arrays;

public class ObjectFall {

public int howLong(int x, int y, String[] obstacles) {
int nowx=x;
int nowy=y;

//System.out.println("X="+x+" Y="+y+":"+Arrays.toString(obstacles));
int[] oy = new int[obstacles.length];
int[] ox1 = new int[obstacles.length];
int[] ox2 = new int[obstacles.length];
for (int i = 0; i < obstacles.length; i++) {
oy[i]=Integer.parseInt(obstacles[i].split(" ")[0]);
ox1[i]=Integer.parseInt(obstacles[i].split(" ")[1]);
ox2[i]=Integer.parseInt(obstacles[i].split(" ")[2]);
}
//System.out.println(Arrays.toString(oy));
//System.out.println(Arrays.toString(ox1));
//System.out.println(Arrays.toString(ox2));
for (int i = 0; i < obstacles.length-1; i++) {
for (int j = i+1; j < obstacles.length; j++) {
if (oy[i]<oy[j]) {
int buff = oy[i];
oy[i]=oy[j];
oy[j]=buff;
buff = ox1[i];
ox1[i]=ox1[j];
ox1[j]=buff;
buff = ox2[i];
ox2[i]=ox2[j];
ox2[j]=buff;
}
}
}
//System.out.println(Arrays.toString(oy));
//System.out.println(Arrays.toString(ox1));
//System.out.println(Arrays.toString(ox2));

int count=0;
for (int i = 0; i < obstacles.length; i++) {
if (oy[i]<=nowy&&ox1[i]<=nowx&&nowx<=ox2[i]) {
count+=(nowy-oy[i]+5);
nowy=oy[i];
nowx=ox2[i];
}
}
count+=(nowy);
nowy=0;
return count;
}

}

[/java]

コメント

タイトルとURLをコピーしました