본문 바로가기
JAVA

백준 6064

by Son 2022. 5. 10.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        Main test = new Main();
    }

    public Main() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer stk;
        int tc = Integer.parseInt(br.readLine());
        for (int i = 0 ; i < tc ; i++){
            stk = new StringTokenizer(br.readLine()," ");
            int N = Integer.parseInt(stk.nextToken());
            int M = Integer.parseInt(stk.nextToken());
            int x = Integer.parseInt(stk.nextToken());
            int y = Integer.parseInt(stk.nextToken());

            int result ;

            if ( N<M){
                result = solution(N,M,x,y);
            }else{
                result=solution(M,N,y,x);
            }
            sb.append(result+"\n");
        }


        System.out.println(sb);

    }

    private int solution(int n, int m, int x, int y) {
        //rotation 단위
        int unit = m-n;

        //최소 공배수까지 반복 숫자
        int time_limit =0;

        //unit ==0 이라면 n 과 m 이 같다는 의미
        if(unit==0){
            //n과 m 같다면, x와y는 같은 값 밖에 안나옴
            if(x==y){
                return y;
            }else{
                //말이안됨
                return -1;
            }
        }else if ( n%unit!=0){
            //서로소 인 경우엔 x값에 대해 y값의 정의역 수가 m 개임
            time_limit =m;
        }else{
            //1이 아닌 최대공약수가 존재함을 의미 따라서 y값의 정의역은 n/unit개
            time_limit = n/ unit;
        }

        //default 자릿수(비순환시)
        int result=x;

        for (int i = 0 ; i <= time_limit+1;i++){

            if(x == y){
                result +=i*n;
                return result;
            }
            //unit만큼 빼주면서 문자 실행
            x =rotate(m,x,unit);
        }



        return -1;
    }

    private int rotate(int standard,int target, int unit){

            if(target - unit<=0){
                target-=unit;
                target+=standard;
            }else{
                target-=unit;
            }


        return target;
    }

}

'JAVA' 카테고리의 다른 글

백준 15649번  (0) 2022.07.04
백준 154  (0) 2022.05.18
[백준] 14500번: 테트로미노  (0) 2022.05.02
백준 1107  (0) 2022.04.28
백준 1476  (0) 2022.04.10