본문 바로가기
Problem Solving

[C++] [백준 1755] 숫자놀이

by tls1107 2021. 7. 27.
728x90
반응형


문제 풀기 전 생각 : 

/*
입력 받은 범위의 숫자들을 
알파벳으로 변환 후 저장한다.
그리고 소트 함수를 이용해 정렬한다.
*/

#include <iostream>
#include <algorithm>
using namespace std;
string num[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
bool comp(pair<string,int> p1,pair<string,int> p2){
  return p1.first < p2.first;
}
int main(){
  string s;
  int n1=4,n2=6;
  cin >> n1 >> n2;
  int n = n2 - n1 + 1;
  pair<string,int> str[n];

  for(int i = n1 ; i <= n2 ; i++){
    s = to_string(i); 
    str[i-n1].first="";
    str[i-n1].second = i;
    for(int j=0 ; j<s.length() ; j++){
      str[i-n1].first += num[(int)(s[j]-'0')] + " ";
    }
  }
  sort(str,str+n,comp);

  for(int i=0 ; i<n ; i++){
    cout << str[i].second << "\n";
  }
  return 0;
}

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

 

1755번: 숫자놀이

79를 영어로 읽되 숫자 단위로 하나씩 읽는다면 "seven nine"이 된다. 80은 마찬가지로 "eight zero"라고 읽는다. 79는 80보다 작지만, 영어로 숫자 하나씩 읽는다면 "eight zero"가 "seven nine"보다 사전순으로

www.acmicpc.net


풀 때 어려웠던 점 또는 느낀점 :

pair를 쓰는것이 더 익숙해졌다.

비슷한 문제들은 금방 풀 수 있을 것 같다!


개선방안 :

#include <bits/stdc++.h>


using namespace std;

string arr[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};

bool cmp(pair<string,int>&a ,pair<string,int> &b){
    return a.first < b.first;
}


int main(){
    int a,b;
    cin >> a >> b;
    vector<pair<string,int>> v;
    for (int i =a ; i <=b ;i++){

        string sti = to_string(i);
        string temp = "";
        for (int j =0 ; j < sti.size(); j++){
            temp += arr[(sti[j])-'0'];
        }
        v.push_back({temp,i});
    }

    sort(v.begin(),v.end(),cmp);
    int cnt =0;
    for(auto x : v) {
        if(cnt %10==0 && cnt != 0) cout << '\n';
        cnt++;
        cout << x.second << " ";
    }

}

나랑 비슷한 접근법을 사용한 코드이다.

이번 문제는 잘 푼것 같아서 기분이 좋다!!

728x90
반응형

댓글