알고리즘/백준

[백준] 21275 폰 호석만 C++

이영재의오른발 2023. 8. 10. 13:38
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <cmath>
 
using namespace std;
 
string a,b;
 
void input() {
    cin >> a >> b;
}
 
int calMax(string str) {
    int result = 0;
    for(int i=0; i<str.size(); i++) {
        if(isalpha(str[i])) {
            int cmp = str[i] - 'a';
            cmp += 11;
            result = max(result, cmp); 
        }
        else { 
            int cmp = str[i] - '0';
            cmp += 1;
            result = max(result, cmp); 
        }
    }
    return result;
}
 
long long calculate(int num, string str) {
    long long result = 0;
    int tmp = 0;
    
    for(int i=str.size()-1; i>=0; i--) {
        int rem;
        if(isalpha(str[i])) {
            rem = str[i] - 'a';
            rem += 10;
        }
        else {
            rem = str[i] - '0';
        }
        result += pow(num, tmp) * rem;
        tmp += 1;
    }
    
    return result;
}
 
void solve() {
    int max_a = calMax(a);
    int max_b = calMax(b);
    
    int cnt = 0;
    long long answer, answer_a, answer_b;
    
    for(int i=max_a; i<=36; i++) {
        for(int j=max_b; j<=36; j++) {
            long long a_tmp = calculate(i, a);
            long long b_tmp = calculate(j, b);
            
            if(i == j) { continue; }
            if(a_tmp == b_tmp && a_tmp >= 0) {
                cnt += 1;
                answer = a_tmp;
                answer_a = i;
                answer_b = j;
            }
        }
    }
    
    if(cnt >= 2) { cout << "Multiple"; }
    else if(cnt == 0) { cout << "Impossible"; }
    else { cout << answer << " " << answer_a << " " << answer_b; }
}
 
int main() {
    input();
    solve();
    
}
cs

 

 

int calMax(string str) {
	int result = 0;
	for(int i=0; i<str.size(); i++) {
		if(isalpha(str[i])) {
			int cmp = str[i] - 'a';
			cmp += 11;
			result = max(result, cmp); 
		}
		else { 
			int cmp = str[i] - '0';
			cmp += 1;
			result = max(result, cmp); 
		}
	}
	return result;
}

 

calMax 메서드에서 그 수의 문자열에 따른 최소 진수를 구한다.

 

	for(int i=max_a; i<=36; i++) {
		for(int j=max_b; j<=36; j++) {
			long long a_tmp = calculate(i, a);
			long long b_tmp = calculate(j, b);
			
			if(i == j) { continue; }
			if(a_tmp == b_tmp && a_tmp >= 0) {
				cnt += 1;
				answer = a_tmp;
				answer_a = i;
				answer_b = j;
			}
		}
	}

 

이후 최소 진수부터 최대진수인 36까지 반복문 전체를 돌며 X를 i진법으로 표현한 값 a_tmp와 X를 j진법으로 표현한 값 b_tmp 를 비교한다.

 

진법 개념만 알고있다면 쉽게 풀 수 있는 단순 구현문제이다.

728x90
반응형