Algorithm/Cases-Study

카잉달력

Xi_kor 2021. 5. 4. 21:34

처음에 m과 x가 같은 경우, n과 y가 같은 경우를 생각을 못해서 제대로 답이 나오질 않았다! 해당 숫자를 x를 기준으로 하여 x가 m보다 작다면 나눴을 때 나머지가 무조건 x이므로 기본 시작 숫자를 x로 잡았다. 같은 경우에는 나머지가 0이므로 기본 시작 숫자는 0이 된다. 그리고 m만큼씩 늘려가면 해당 숫자는 무조건 m으로 나눴을 때 나머지가 기본 시작 숫자(0 또는 x)가 된다. 따라서 나눴을 때 나머지가 y의 기본 숫자가 되는지만 탐색해주었다.

#include <iostream>
#include <cstring>
using namespace std;

int ch[40010];

int main(){
    int tc;
    cin>>tc;
    
    for(int T=1; T<=tc; T++){
        memset(ch, 0, sizeof(ch));
        int m, n, x, y;
        cin>>m>>n>>x>>y;
        int xnum, ynum;
        
        if(m==x) xnum=0;
        else xnum=x;
        
        if(n==y) ynum=0;
        else ynum=y;
        
        int num=xnum;
        int status=0;
        int cnt=0;
        while(1){
            if(num%n==ynum){
                status=1;
                break;
            }
            num=num+m;
            cnt++;
            
            if(cnt>n) break;
        }
        if(status==1){
            cout<<num<<endl;
        }
        else cout<<"-1"<<endl;
        
    }
    return 0;
}