본문 바로가기

문제풀이/C 문제풀이

[HackerRank]Kangaroo

문제

You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity).
The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump.
The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump.
You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

Function Description
Complete the function kangaroo in the editor below. It should return YES if they reach the same position at the same time, or NO if they don't.
Input Format
A single line of four space-separated integers denoting the respective values of x1, v1, x2, and v2.
Output Format
Print YES if they can land on the same location at the same time; otherwise, print NO.

Note: The two kangaroos must land at the same location after making the same number of jumps.

CODE

char* kangaroo(int x1, int v1, int x2, int v2) {
    if (((v1 >= v2) && (x1 > x2))||((v1 <= v2) && (x1 < x2))) return "NO"; // 절대로 따라잡을 수 없는 경우에는 "NO" 반환
    else {
        for(int a=x1, b=x2;;a+=v1, b+=v2) { // a, b: x1, x2의 현재 위치
            if (a == b) return "YES"; // x1과 x2가 동일하다면 "YES" 반환
            else if (((x1 < x2) && (a > b))||((x1 > x2) && (a < b))) return "NO";
            // 둘이 같은 적 없었는데 하나가 다른 하나를 추월한다면 더 이상 같은 위치에 있을 수 없으므로 "NO"반환
        }
    }
}

감상

경우의 수를 나눠서 구했다

'문제풀이 > C 문제풀이' 카테고리의 다른 글

[SWEA]3431 준환이의 운동관리  (0) 2019.09.08
[HackerRank]Between Two Sets  (0) 2019.07.30
[HackerRank]Breaking the Records  (0) 2019.07.08
[HackerRank]Apple and Orange  (0) 2019.07.03
[HackerRank]Grading Students  (0) 2019.07.01