본문 바로가기
개발 노트/백준, 프로그래머스 풀이

[백준 12871/c++] 무한 문자열

by tokkiC 2022. 7. 2.

문자열 a와 b를 무한히 늘렸을때 두 문자열은 같은지를 묻는 문제이다

a길이와 b길이의 최소공배수를 구하고 그 길이가 될때까지 각각 자기복제를 하여 새로 만든 두 문자열이

같은지를 비교하면 되는 문제이다

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

 

12871번: 무한 문자열

첫째 줄에 s, 둘째 줄에 t가 주어진다. 두 문자열 s와 t의 길이는 50보다 작거나 같은 자연수이고, 알파벳 소문자로만 이루어져 있다. 

www.acmicpc.net

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

int gcd(int x, int y){
	int z;
	while(y!=0){
		z=x%y;
		x=y;	
		y=z;
	}
	return x;
}

int lcm(int x, int y){
	return x*y/gcd(x, y);
}

int main(){
	
	string a, b;
	
	cin >> a >> b;
	
	string atm=a;
	string btm=b;
	
	int al=a.length();		
	int bl=b.length();
	
	int ablcm=lcm(al, bl);	
	
	if(a==b){
		cout << 1 << "\n";
		return 0;
	}
	
	while(al!=ablcm){	
		atm+=a;
		al+=a.length();
	}
	
	while(bl!=ablcm){	
		btm+=b;
		bl+=b.length();
	}

	
	if(atm==btm){
		cout << 1 << "\n";
	} else {
		cout << 0 << "\n";
	}
	
	return 0;
}

댓글