백준 알고리즘(C++)

백준 1213번 팰린드롬 만들기( C++ )

coding232624 2024. 2. 25. 23:56

문제

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

 

1213번: 팰린드롬 만들기

첫째 줄에 문제의 정답을 출력한다. 만약 불가능할 때는 "I'm Sorry Hansoo"를 출력한다. 정답이 여러 개일 경우에는 사전순으로 앞서는 것을 출력한다.

www.acmicpc.net

 

해설

map<string,int> mp;활용하기

for(char n : name) mp[n]++; 카운팅

if(name.length() & 0) 짝수판단

if(alp_len & 1) 홀수 판단

 

 

코드

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
#include<bits/stdc++.h>
using namespace std;
 
int check,alp_len;
string name,ret,center;
map<char,int> mp;
 
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    
    cin >> name;
    for(char n : name) mp[n]++;
    
//    짝수면 True 
    if(name.length() & 0){
        check =0;
    }
    else{
        check = 1;
    }
    
    for(int i = 'A'; i<='Z';i++){
        alp_len = mp[i];
//        홀수면 True 
        if(alp_len & 1){
            if(check <= 0){
                cout << "I'm Sorry Hansoo";
                return 0;
            }
            center = i;
            check --;
            mp[i]--;
        }
        int alp_len_two = int(alp_len / 2);
//        cout << i << "   " << alp_len_two;
        for(int j =0; j < alp_len_two;j++){
            ret += i;
            mp[i]--;
        }    
    }
    ret += center;
    for (int i = 'Z';i>='A'; i--){
        alp_len = mp[i];
        for(int j =0; j < alp_len; j++){
            ret += i;
        }
    }
    cout << ret;
    return 0;
}
cs