ALG/ALG Solve

[C++] 백준 10610번 - 30

jh2ee 2023. 7. 14. 21:46

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

 

10610번: 30

어느 날, 미르코는 우연히 길거리에서 양수 N을 보았다. 미르코는 30이란 수를 존경하기 때문에, 그는 길거리에서 찾은 수에 포함된 숫자들을 섞어 30의 배수가 되는 가장 큰 수를 만들고 싶어한

www.acmicpc.net

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    long long sum=0;
    
    string n;
    cin>>n;
    sort(n.begin(), n.end(), greater<>());

    if(n[n.length()-1]!='0') cout<<-1;
    else{
        for(auto o:n){
            sum+= o-'0';
        }
        if(sum%3!=0) cout<<-1;
        else cout<< n;
    }

    return 0;
}

꽤 오래 걸린 문제... 30의 배수 판별은 쉽게 할 수 있었지만 string으로 받아와 처리하는 과정에 애를 먹었다. sort를 사용하면 쉽게 처리할 수 있었다.

그리고 원래 풀이

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

int number[10];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    long long sum=0;
    
    string n;
    cin>>n;

    for(int i=0;i<n.length();i++){
        int k=int(n[i]-'0');
        sum+=k;
        number[k]++;
    }
    if(sum%3!=0||number[0]==0) cout<<-1<<"\n";
    else{
        for(int i=9;i>=0;i--){
            while(number[i]>0){
                cout<<i;
                number[i]--;
            }
        }
    }
    cout<<endl;

    return 0;
}

sort하는 대신 배열에 각 숫자의 수를 저장하여 출력하게 했다.