Algorithm

[BOJ] 6064번 : 카잉 달력

rudgh99_algo 2024. 9. 25. 08:35

1. problem : 

https://www.acmicpc.net/problem/6064

 

2. solution 1 :

#include <bits/stdc++.h>
using namespace std;

int gcd(int a, int b) {
	if (b == 0) return a; 
	return gcd(b, a % b);
}

int lcm(int a, int b) {
	return a / gcd(a, b) * b;
}
int solve(int m, int n, int x, int y) {
	if (x == m) x = 0; 
	if (y == n) y = 0; 
	int l = lcm(m, n); 
	for (int i = x; i <= l; i += m) {
		if (i == 0) continue; 
		if (i % n == y) {
			return i;
		}
	}
	return -1;


}
int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0); 
	int t, m, n, x, y;
	cin >> t;
	while (t--) {
		cin >> m >> n >> x >> y; 
		cout << solve(m, n, x, y) << '\n';
	}
}

source code 출처 : https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x12/solutions/6064.cpp

 

basic-algo-lecture/0x12/solutions/6064.cpp at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

이 문제는 최소공배수를 활용해서 , l을 지정한 다음, i % m == x를 만족시키는 값들로, i % n == y를 만족시키는 값들을 찾아가는 방식으로 구현되었다. i == 0일 때는 예외처리이다. 그 이유는 , i == 0일 때는 x  == m이라는 것이고, 이때 y가 n이라면 y ==0이 된다. 따라서, return 값이 0이 되어, 잘못된 답을 출력할 수 있다. 따라서, i == 0일 때는 continue를 해준다고 한다. 아직 100% 이해는 못했고, 언젠가는 이해가 되기를 바란다.