본문 바로가기

programming/algorithm 공부

[Algorithm] 캥거루 두 마리


> Quest.

There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location  and moves at a rate of  meters per jump. The second kangaroo starts at location  and moves at a rate of  meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?



> Input.

Input Format

A single line of four space-separated integers denoting the respective values of , , , and .



> Output.

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.



> solve

Summary

요약하면, 캥거루 두마리는 각각 시작 위치 x1, x2 에서 움직입니다. 각각 속도는 v1, v2 의 속도를 갖습니다. 둘은 만날 수 있는가 하는 문제입니다.


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

bool fn_sameloc(int x1, int v1, int x2, int v2){
    bool item = (x1+v1 > x2+v2 ? true : false);
    int times = 0;
    while(true){
        if(x1 == (v2 - v1) * times + x2){
            return true;
        }
        times++;
        if((item && x2+v2*times > x1+v1*times) || (!item && x2+v2*times < x1+v1*times)){
            return false;
        }
    }
}

int main(){
    int x1; 
    int v1; 
    int x2; 
    int v2; 
    scanf("%d %d %d %d",&x1,&v1,&x2,&v2);
    
    printf("%s", (fn_sameloc(x1,v1, x2,v2) ? "YES" : "NO"));
    return 0;
}




반응형

'programming > algorithm 공부' 카테고리의 다른 글

[Algorithm] Connecting Towns  (0) 2017.10.09
[Algorithm] Handshake / 악수  (0) 2017.10.09
[Algorithm] Divisible Sum Pairs  (0) 2017.10.09
[Algorithm] 사과나무와 오렌지나무  (0) 2017.10.09
[Algorithm] Angry Professor  (0) 2017.10.09