6번 크로아티아 알파벳

문제

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다.

 

크로아티아 알파벳 변경
č c=
ć c-
dz=
đ d-
lj lj
nj nj
š s=
ž z=

 

예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다. dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다.

 

입력

첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 '-', '='로만 이루어져 있다.

 

단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다.

 

출력

입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

 

입력되는 문자열에서 대응하는 크로아티아 문자열이 있는지 확인하여 글자 수를 구한다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    string input;
    cin >> input;
    int char_cnt = 0;
    string str_arr[8] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
    for (int i = 0; i < input.length(); i++){
        bool matched = false;
        for (int j = 0; j < 8; j++){
            string croatian_char = str_arr[j];
            if (input.substr(i, croatian_char.length()) == croatian_char){
                char_cnt++;
                i += croatian_char.length() - 1;
                matched = true;
                break;
            }
        }
        if (!matched){
            char_cnt++;
        }
    }
    cout << char_cnt;
    return 0;
}

 

크로아티아 문자를 배열에 저장해 두고 입력된 문자열을 순회하면서 크로아티아 문자가 포함되어 있는지 검사한다.

 

검사할 때 크로아티아 문자 배열을 순회하면서 하나씩 입력된 문자열의 인덱스를 기준으로 동일한지 검사한다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string[] str_arr = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
        string input = Console.ReadLine();
        int char_cnt = 0;
        for (int i = 0; i < input.Length; i++){
            bool char_matched = false;
            for (int j = 0; j < str_arr.Length; j++){
                string croatian_char = str_arr[j];
                if (i + croatian_char.Length <= input.Length &&
                    input.Substring(i, croatian_char.Length) == croatian_char){
                    char_cnt++;
                    i += croatian_char.Length - 1;
                    char_matched = true;
                    break;
                }
            }
            if (!char_matched) char_cnt++;
        }
        Console.WriteLine(char_cnt);
    }
}

 

 

Python

input_str = input()
str_arr = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="]
char_cnt = 0
i = 0
while i < len(input_str):
    is_char_matched = False
    for croatian_char in str_arr:
        if input_str[i:i+len(croatian_char)] == croatian_char:
            char_cnt += 1
            i += len(croatian_char)
            is_char_matched = True
            break
    if not is_char_matched:
        char_cnt += 1
        i += 1
print(char_cnt)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim();
const croatian_chars = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="];
let char_cnt = 0;
for (let i = 0; i < input.length; i++){
    let is_char_matched = false;
    for (let j = 0; j < croatian_chars.length; j++){
        const croatian_char = croatian_chars[j];
        if (input.slice(i, i + croatian_char.length) === croatian_char){
            char_cnt += 1;
            i += croatian_char.length - 1;
            is_char_matched = true;
            break;
        }
    }
    if (!is_char_matched){
        char_cnt += 1;
    }
}
console.log(char_cnt);

 

7번 그룹 단어 체커

문제

그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다. 예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때문에 그룹 단어이지만, aabbbccb는 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다. 

 

단어 N개를 입력으로 받아 그룹 단어의 개수를 출력하는 프로그램을 작성하시오.

 

입력

첫째 줄에 단어의 개수 N이 들어온다. N은 100보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 단어가 들어온다. 단어는 알파벳 소문자로만 되어있고 중복되지 않으며, 길이는 최대 100이다.

 

출력

첫째 줄에 그룹 단어의 개수를 출력한다.

 

N개의 입력을 받아서 해당 단어가 연속되는 문자인지 확인을 해야 한다. 연속은 동일한 문자 사이에 다른 문자가 등장했을 때 연속성이 깨진다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    cin >> n;
    
    string word;
    int word_cnt = 0;
    while(cin >> word){
        bool is_seq_word = true;
        int char_arr[26] = {0};
        char last_char = '\0';
        for (char c : word){
            if (c != last_char){
                if (char_arr[c - 'a'] != 0){
                    is_seq_word = false;
                    break;
                }
                char_arr[c - 'a'] = 1;
            }
            last_char = c;
        }
        if (is_seq_word) 
            word_cnt++;
    }
    cout << word_cnt;
    return 0;
}

 

 

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        int word_cnt = 0;
        for (int i = 0; i < n; i++){
            char last_char = '\0';
            int[] char_arr = new int[26];
            string word = Console.ReadLine();
            bool is_seq_word = true;
            foreach (char c in word){
                if (c != last_char){
                    if (char_arr[c - 'a'] != 0){
                        is_seq_word = false;
                        break;
                    }
                    char_arr[c - 'a'] = 1;
                }
                last_char = c;
            }
            if (is_seq_word)
                word_cnt++;
        }
        Console.WriteLine(word_cnt);
    }
}

 

Python

n = int(input())
word_cnt = 0;
for i in range(n):
    word = input();
    is_seq_word = True
    last_char = '\0'
    char_arr = [0] * 26
    for c in word:
        if c != last_char:
            if char_arr[ord(c) - ord('a')] != 0:
                is_seq_word = False
                break
            char_arr[ord(c) - ord('a')] = 1
        last_char = c
    if is_seq_word:
        word_cnt += 1
print(word_cnt)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
const n = parseInt(input[0]);
let word_cnt = 0;
for (let i = 1; i <= n; i++){
    const char_arr = Array(26).fill(0);
    const word = input[i];
    let is_seq_word = true;
    let last_char = '\0';
    for (const c of word){
        if (c !== last_char){
            if (char_arr[c.charCodeAt(0) - 'a'.charCodeAt(0)]){
                is_seq_word = false;
                break;
            }
            char_arr[c.charCodeAt(0) - 'a'.charCodeAt(0)] = 1;
        }
        last_char = c;
    }
    if (is_seq_word){
        word_cnt++;
    }
}
console.log(word_cnt);

 

8번 너의 평점은

문제

인하대학교 컴퓨터공학과를 졸업하기 위해서는, 전공평점이 3.3 이상이거나 졸업고사를 통과해야 한다. 그런데 아뿔싸, 치훈이는 깜빡하고 졸업고사를 응시하지 않았다는 사실을 깨달았다! 

 

치훈이의 전공평점을 계산해 주는 프로그램을 작성해 보자. 

 

전공평점은 전공과목별 (학점 × 과목평점)의 합을 학점의 총합으로 나눈 값이다. 

 

인하대학교 컴퓨터공학과의 등급에 따른 과목평점은 다음 표와 같다.

 

A+ 4.5
A0 4.0
B+ 3.5
B0 3.0
C+ 2.5
C0 2.0
D+ 1.5
D0 1.0
F 0.0

 

P/F 과목의 경우 등급이 P 또는 F로 표시되는데, 등급이 P인 과목은 계산에서 제외해야 한다. 

 

과연 치훈이는 무사히 졸업할 수 있을까?

 

입력

20줄에 걸쳐 치훈이가 수강한 전공과목의 과목명, 학점, 등급이 공백으로 구분되어 주어진다.

 

출력

치훈이의 전공평점을 출력한다. 

 

정답과의 절대오차 또는 상대오차가 \(10^{-4}\) 이하이면 정답으로 인정한다.

 

제한

- 1 ≤ 과목명의 길이 ≤ 50

- 과목명은 알파벳 대소문자 또는 숫자로만 이루어져 있으며, 띄어쓰기 없이 주어진다. 입력으로 주어지는 모든 과목명은 서로 다르다.

- 학점은 1.0,2.0,3.0,4.0중 하나이다.

- 등급은 A+, A0, B+, B0, C+, C0, D+, D0, F, P 중 하나이다.

- 적어도 한 과목은 등급이 P가 아님이 보장된다.

 

20과목 정보가 이름, 점수, 등급으로 각 줄에 입력된다.

 

P가 아닌 등급일 때만 점수를 계산한다.

 

C++

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
    float total_score = 0.0f;
    float sum_score = 0.0f;
    for (int i = 0; i < 20; i++){
        string name;
        float score;
        string grade;
        float grade_score;
        cin >> name >> score >> grade;
        if (grade == "A+"){
            grade_score = 4.5;
        }
        else if (grade == "A0"){
            grade_score = 4.0;
        }
        else if (grade == "B+"){
            grade_score = 3.5;
        }
        else if (grade == "B0"){
            grade_score = 3.0;
        }
        else if (grade == "C+"){
            grade_score = 2.5;
        }
        else if (grade == "C0"){
            grade_score = 2.0;
        }
        else if (grade == "D+"){
            grade_score = 1.5;
        }
        else if (grade == "D0"){
            grade_score = 1.0;
        }
        else if (grade == "F"){
            grade_score = 0.0;
        }
        
        if (grade != "P"){
            sum_score += score;
            total_score += score * grade_score;
        }
    }
    float result = total_score / sum_score;
    cout << fixed << setprecision(6) << result;
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        float sum_score = 0f;
        float total_score = 0f;
        for (int i = 0; i < 20; i++){
            string str = Console.ReadLine();
            string[] str_arr = str.Split();
            string name = str_arr[0];
            float score = float.Parse(str_arr[1]);
            string grade = str_arr[2];
            float grade_score = 0f;
            if (grade == "A+"){
                grade_score = 4.5f;
            }
            else if (grade == "A0"){
                grade_score = 4.0f;
            }
            else if (grade == "B+"){
                grade_score = 3.5f;
            }
            else if (grade == "B0"){
                grade_score = 3.0f;
            }
            else if (grade == "C+"){
                grade_score = 2.5f;
            }
            else if (grade == "C0"){
                grade_score = 2.0f;
            }
            else if (grade == "D+"){
                grade_score = 1.5f;
            }
            else if (grade == "D0"){
                grade_score = 1.0f;
            }
            else if (grade == "F"){
                grade_score = 0.0f;
            }
            if (grade != "P"){
                sum_score += score;
                total_score += score * grade_score;
            }
        }
        float result = total_score / sum_score;
        Console.WriteLine(result);
    }
}

 

Python

import sys
sum_score = 0;
total_score = 0;
for i in range(20):
    name, score, grade = sys.stdin.readline().strip().split()
    score = float(score)
    grade_score = 0;
    if grade != "P":
        if grade == "A+":
            grade_score = 4.5
        elif grade == "A0":
            grade_score = 4.0
        elif grade == "B+":
            grade_score = 3.5
        elif grade == "B0":
            grade_score = 3.0
        elif grade == "C+":
            grade_score = 2.5
        elif grade == "C0":
            grade_score = 2.0
        elif grade == "D+":
            grade_score = 1.5
        elif grade == "D0":
            grade_score = 1.0
        elif grade == "F":
            grade_score = 0.0
        sum_score += score
        total_score += score * grade_score
result = total_score / sum_score
print(f"{result:.6f}")

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('\n');
let total_score = 0.0;
let sum_score = 0.0;
for (let i = 0; i < 20; i++){
    const str = input[i].split(' ');
    const name = str[0];
    const score = parseFloat(str[1]);
    const grade = str[2];
    let grade_score = 0.0;
    if (grade === "A+")
    {
        grade_score = 4.5;
    }
    else if (grade === "A0")
    {
        grade_score = 4.0;
    }
    else if (grade === "B+")
    {
        grade_score = 3.5;
    }
    else if (grade === "B0")
    {
        grade_score = 3.0;
    }
    else if (grade === "C+")
    {
        grade_score = 2.5;
    }
    else if (grade === "C0")
    {
        grade_score = 2.0;
    }
    else if (grade === "D+")
    {
        grade_score = 1.5;
    }
    else if (grade === "D0")
    {
        grade_score = 1.0;
    }
    else if (grade === "F")
    {
        grade_score = 0.0;
    }
    if (grade != "P"){
        sum_score += score;
        total_score += score * grade_score;
    }
}
const result = total_score / sum_score;
console.log(result.toFixed(6));
728x90
반응형

1번 새싹

문제

아래 예제와 같이 새싹을 출력하시오.

 

입력

입력은 없다.

 

출력

새싹을 출력한다.

 

         ,r'"7
r`-_   ,'  ,/
 \. ". L_r'
   `~\/
      |
      |

 

예제 출력의 모양대로 출력을 한다.

 

C++

#include <iostream>
using namespace std;
int main(){
    cout << "         ,r\'\"7" << "\n";
    cout << "r`-_   ,\'  ,/" << "\n";
    cout << " \\. \". L_r\'" << "\n";
    cout << "   `~\\/" << "\n";
    cout << "      |" << "\n";
    cout << "      |" << "\n";
    return 0;
}

 

 

C#

using System;
class Program{
    static void Main(string[] args){
        Console.WriteLine("         ,r\'\"7");
        Console.WriteLine("r`-_   ,\'  ,/");
        Console.WriteLine(" \\. \". L_r\'");
        Console.WriteLine("   `~\\/");
        Console.WriteLine("      |");
        Console.WriteLine("      |");
    }
}

 

Python

print("         ,r\'\"7")
print("r`-_   ,\'  ,/")
print(" \\. \". L_r\'")
print("   `~\\/")
print("      |")
print("      |")

 

Node.js

console.log("         ,r\'\"7");
console.log("r`-_   ,\'  ,/");
console.log(" \\. \". L_r\'");
console.log("   `~\\/");
console.log("      |");
console.log("      |");

 

2번 킹, 퀸, 룩, 비숍, 나이트, 폰

문제

동혁이는 오래된 창고를 뒤지다가 낡은 체스판과 피스를 발견했다. 

 

체스판의 먼지를 털어내고 걸레로 닦으니 그럭저럭 쓸만한 체스판이 되었다. 하지만, 검은색 피스는 모두 있었으나, 흰색 피스는 개수가 올바르지 않았다. 

 

체스는 총 16개의 피스를 사용하며, 킹 1개, 퀸 1개, 룩 2개, 비숍 2개, 나이트 2개, 폰 8개로 구성되어 있다. 

 

동혁이가 발견한 흰색 피스의 개수가 주어졌을 때, 몇 개를 더하거나 빼야 올바른 세트가 되는지 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 동혁이가 찾은 흰색 킹, 퀸, 룩, 비숍, 나이트, 폰의 개수가 주어진다. 이 값은 0보다 크거나 같고 10보다 작거나 같은 정수이다.

 

출력

첫째 줄에 입력에서 주어진 순서대로 몇 개의 피스를 더하거나 빼야 되는지를 출력한다. 만약 수가 양수라면 동혁이는 그 개수만큼 피스를 더해야 하는 것이고, 음수라면 제거해야 하는 것이다.

 

입력된 체스말의 개수가 한 세트가 될 수 있도록 개수를 맞춘다.

 

C++

#include <iostream>
using namespace std;
int main(){
    int chess_set[] = {1, 1, 2, 2, 2, 8 };
    int need_val[6];
    int count;
    for (int i = 0; i < 6; i++){
        cin >> count;
        need_val[i] = chess_set[i] - count;
    }
    for (int i : need_val){
        cout << i << " ";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int[] chess_set = { 1, 1, 2, 2, 2, 8 };
        string[] input_arr = Console.ReadLine().Split();
        for (int i = 0; i < 6; i++){
            int val = int.Parse(input_arr[i]);
            int need_val = chess_set[i] - val;
            Console.Write($"{need_val} ");
        }
    }
}

 

Python

chess_set = [1, 1, 2, 2, 2, 8]
input_set = list(map(int, input().split()))
for i in range(6):
    val = chess_set[i] - input_set[i]
    print(f'{val} ', end='')

 

Node.js

const fs = require('fs');
const input_set = fs.readFileSync('/dev/stdin','utf8').split(' ').map(Number);
const chess_set = [1, 1, 2, 2, 2, 8]
for (let i = 0; i < 6; i++){
    const val = chess_set[i] - input_set[i];
    process.stdout.write(`${val} `);
}

 

3번 별 찍기 - 7

문제

예제를 보고 규칙을 유추한 뒤에 별을 찍어 보세요.

 

입력

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

 

출력

첫째 줄부터 2 ×N-1번째 줄까지 차례대로 별을 출력한다.

 

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

 

입력된 숫자와 규칙을 적용해서 별을 찍는 문제이다. 입력된 N을 사용해서 2N -1줄에 별을 찍는다.

 

각 줄에는 시행 횟수 i의 2i - 1 개의 별을 찍고 i가 N보다 클 때부터 2i - N 개의 별을 찍는다.

 

공백도 필요한데 공백은 N - i, i가 N보다 커지면 i - N 이 된다.

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    int n;
    cin >> n;
    for (int i = 1; i <= 2 * n - 1; i++){
        int space_count = n - i;
        int star_count = 2 * i - 1;
        if (i > n){
            space_count = i - n;
            star_count = 2 * (2 * n - i) - 1;
        }
        string space(space_count, ' ');
        string star(star_count, '*');
        cout << space << star << "\n";
    }
    return 0;
}

 

C#

using System;
class Program{
    static void Main(string[] args){
        int n = int.Parse(Console.ReadLine());
        int line = 2 * n;
        for (int i = 1; i < line; i++){
            int space_cnt = n - i;
            int star_cnt = 2 * i - 1;
            if (i > n){
                space_cnt = i - n;
                star_cnt = 2 * (line - i) - 1;
            }
            string space = new string(' ', space_cnt);
            string star = new string('*', star_cnt);
            Console.WriteLine($"{space}{star}");
        }
    }
}

 

Python

n = int(input())
line = 2 * n
for i in range(1, line):
    if i > n:
        space_cnt = i - n
        star_cnt = 2 * (line - i) - 1
    else:
        space_cnt = n - i
        star_cnt = 2 * i - 1
    space = ' ' * space_cnt
    star = '*' * star_cnt
    print(f"{space}{star}")

 

Node.js

const fs = require('fs');
const n = parseInt(fs.readFileSync('/dev/stdin','utf8'));
const line = 2 * n;
for (let i = 1; i < line; i++){
    let space_cnt;
    let star_cnt;
    if (i > n){
        space_cnt = i - n;
        star_cnt = 2 * (line - i) - 1;
    }
    else{
        space_cnt = n - i;
        star_cnt = 2 * i - 1;
    }
    const space = ' '.repeat(space_cnt);
    const star = '*'.repeat(star_cnt);
    console.log(`${space}${star}`);
}

 

4번 팰린드롬인지 확인하기

문제

알파벳 소문자로만 이루어진 단어가 주어진다. 이때, 이 단어가 팰린드롬인지 아닌지 확인하는 프로그램을 작성하시오. 

 

팰린드롬이란 앞으로 읽을 때와 거꾸로 읽을 때 똑같은 단어를 말한다. 

 

level, noon은 팰린드롬이고, baekjoon, online, judge는 팰린드롬이 아니다.

 

입력

첫째 줄에 단어가 주어진다. 단어의 길이는 1보다 크거나 같고, 100보다 작거나 같으며, 알파벳 소문자로만 이루어져 있다.

 

출력

첫째 줄에 팰린드롬이면 1, 아니면 0을 출력한다.

 

팰린드롬이란 기러기, 역삼역, 스위스 같은 건가 보다. 

 

입력된 문자열을 뒤집었을 때와 비교해서 동일하면 1, 아니면 0을 출력한다.

 

C++

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    string str;
    cin >> str;
    string rev_str = str;
    reverse(str.begin(), str.end());
    int result = 0;
    if (str == rev_str)
        result = 1;
    else
        result = 0;
    cout << result;
    return 0;
}

 

reverse는 값을 반환하지 않기 때문에 rev_str에 str을 할당 후에 이 문자열을 뒤집어 준다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string str = Console.ReadLine();
        char[] rev_str_arr = str.ToCharArray();
        Array.Reverse(rev_str_arr);
        string rev_str = new string(rev_str_arr);
        int result = 0;
        if (str == rev_str)
            result = 1;
        else
            result = 0;
        Console.Write(result);
    }
}

 

Python

input_str = input()
rev_str = input_str[::-1]
result = 0
if input_str == rev_str:
    result = 1
else:
    result = 0
print(result)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim();
const rev_input = input.split('').reverse().join('');
let result = 0;
if (input === rev_input)
    result = 1;
else
    result = 0;
console.log(result);

 

5번 단어 공부

문제

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

 

입력

첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어진다. 주어지는 단어의 길이는 1,000,000을 넘지 않는다.

 

출력

첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력한다. 단, 가장 많이 사용된 알파벳이 여러 개 존재하는 경우에는 ?를 출력한다.

 

알파벳 개수만큼 배열을 선언하고 해당 알파벳이 나올 때 인덱스에 값을 증가시키면 될 듯하다.

 

C++

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main(){
    int str_count[26] = {0};
    string str;
    cin >> str;
    transform(str.begin(), str.end(), str.begin(), ::toupper);
    for (char c : str){
        int idx = c - 'A';
        str_count[idx]++;
    }
    int* max_iter = max_element(str_count, str_count + 26);
    int max_index = distance(str_count, max_iter);
    int max_count = *max_iter;
    char max_char = max_index + 'A';
    int duplicate_count = 0;
    for (int i : str_count){
        if (i == max_count){
            duplicate_count++;
            if (duplicate_count > 1)
                break;
        }
    }
    if (duplicate_count > 1)
        cout << "?";
    else
        cout << max_char;
    return 0;
}

 

입력에 대소문자가 모두 들어오기 때문에 문자열을 소문자 또는 대문자로 통일시킨 다음 비교를 진행한다.

 

대문자로 변환시키기 위해서 algorithm의 transform과 cctype의 ::toupper를 사용한다. 소문자는 ::tolower

 

각 문자의 등장 횟수 중 가장 큰 수를 구한 다음 해당 횟수가 또 존재하는지 검사하여 ? 또는 해당 문자의 대문자를 출력한다.

 

C#

using System;
using System.Linq;
class Program{
    static void Main(string[] args){
        string str = Console.ReadLine().ToUpper();
        int[] char_count = new int[26];
        foreach(char c in str){
            char_count[c - 'A']++;
        }
        int max_count = char_count.Max();
        int max_count_index = Array.IndexOf(char_count, max_count);
        int duplicate_count = char_count.Count(x => x == max_count);
        if (duplicate_count > 1){
            Console.WriteLine("?");
        }
        else{
            Console.WriteLine((char)(max_count_index + 'A'));
        }
    }
}

 

Python

s = input().upper()
str_cnt = [0] * 26
for c in s:
    idx = ord(c) - ord('A')
    str_cnt[idx] += 1
max_cnt = max(str_cnt)
max_idx = 0
duplicate_cnt = 0
for i in range(26):
    if str_cnt[i] == max_cnt:
        duplicate_cnt += 1
        max_idx = i
        if duplicate_cnt > 1:
            break
if duplicate_cnt > 1:
    print("?")
else:
    print(chr(max_idx + ord('A')))

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').toUpperCase();
const str_cnt = new Array(26).fill(0);
for (const c of input){
    const i = c.charCodeAt(0) - 'A'.charCodeAt(0);
    str_cnt[i]++;
}
const max = Math.max(...str_cnt);
let max_idx = 0;
let duplicate_cnt = 0;
for (let i = 0; i < 26; i++){
    if (str_cnt[i] === max){
        duplicate_cnt++;
        max_idx = i;
        if (duplicate_cnt > 1)
            break;
    }
}
if (duplicate_cnt > 1)
    console.log("?");
else
    console.log(String.fromCharCode(max_idx + 'A'.charCodeAt(0)));

 

728x90
반응형

10번 다이얼

문제

상근이의 할머니는 아래 그림과 같이 오래된 다이얼 전화기를 사용한다.

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

 

전화를 걸고 싶은 번호가 있다면, 숫자를 하나를 누른 다음에 금속 핀이 있는 곳까지 시계방향으로 돌려야 한다. 숫자를 하나 누르면 다이얼이 처음 위치로 돌아가고, 다음 숫자를 누르려면 다이얼을 처음 위치에서 다시 돌려야 한다.

 

숫자 1을 걸려면 총 2초가 필요하다. 1보다 큰 수를 거는 데 걸리는 시간은 이보다 더 걸리며, 한 칸 옆에 있는 숫자를 걸기 위해선 1초씩 더 걸린다.

 

상근이의 할머니는 전화번호를 각 숫자에 해당하는 문자로 외운다. 즉, 어떤 단어를 걸 때, 각 알파벳에 해당하는 숫자를 걸면 된다. 예를 들어, UNUCIC는 868242와 같다.

 

할머니가 외운 단어가 주어졌을 때, 이 전화를 걸기 위해서 필요한 최소 시간을 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 알파벳 대문자로 이루어진 단어가 주어진다. 단어의 길이는 2보다 크거나 같고, 15보다 작거나 같다.

 

출력

첫째 줄에 다이얼을 걸기 위해서 필요한 최소 시간을 출력한다.

 

문제가 좀 복잡해 보인다. 2번부터 알파벳이 들어가 있고 7, 9에는 4개, 나머지 번호는 3개씩 번호가 있다.

 

 

 

단어가 주어질 때 걸리는 시간을 출력해야 하므로 대응하는 번호를 누르는 데 걸리는 시간을 계산해야 한다.

 

65 - 90

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    cin >> s;
    int sum_time = 0;
    for (int i = 0; i < s.length(); i++){
        int n = s[i] - 'A';
        if (n < 3) //2
            sum_time += 3;
        else if (n < 6) //3
            sum_time += 4;
        else if (n < 9) // 4
            sum_time += 5;
        else if (n < 12) // 5
            sum_time += 6;
        else if (n < 15) // 6
            sum_time += 7;
        else if (n < 19) // 7
            sum_time += 8;
        else if (n < 22) // 8
            sum_time += 9;
        else             // 9
            sum_time += 10;
    }
    cout << sum_time;
    return 0;
}

 

일단 조건에 맞춰서 코드를 작성해 본다.

 

조금 더 간소화시켜서 다이얼의 걸리는 시간 정보를 배열에 모두 담고 이 배열에서 걸리는 시간을 꺼내 쓰는 방법으로 풀어본다.

 

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    cin >> s;
    int dial_times[26] = {
        3, 3, 3,  // 2)A, B, C
        4, 4, 4,  // 3)D, E, F
        5, 5, 5,  // 4)G, H, I
        6, 6, 6,  // 5)J, K, L
        7, 7, 7,  // 6) M, N, O
        8, 8, 8, 8,  // 7) P, Q, R, S
        9, 9, 9,  // 8) T, U, V
        10, 10, 10, 10  // 9) W, X, Y, Z
    };
        
    int sum_time = 0;
    for (char c : s){
        sum_time += dial_times[c - 'A'];
    }
    cout << sum_time;
    return 0;
}

 

알파벳마다 대응하는 배열의 인덱스에 걸리는 시간 정보를 저장해서 조건문 없이 걸리는 시간을 가져와서 사용할 수 있다.

 

배열로 표현한 게 좀 더 보기 쉽고 수정도 편할 거 같아 보인다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string s = Console.ReadLine();
        int[] dial_times = new int[26]{
            3, 3, 3,       // 2) A, B, C
            4, 4, 4,       // 3) D, E, F
            5, 5, 5,       // 4) G, H, I
            6, 6, 6,       // 5) J, K, L
            7, 7, 7,       // 6) M, N, O
            8, 8, 8, 8,    // 7) P, Q, R, S
            9, 9, 9,       // 8) T, U, V
            10, 10, 10, 10 // 9) W, X, Y, Z
        };
        int sum_time = 0;
        foreach(char c in s){
            sum_time += dial_times[c - 'A'];
        }
        Console.WriteLine(sum_time);
    }
}

 

떠오른 방법 중에는 이렇게 하는 게 제일 간단한 거 같아서 다른 언어들도 동일한 방식으로 진행해 본다.

 

Python

s = input()
dial_times = [
    3, 3, 3,       # 2) A, B, C
    4, 4, 4,       # 3) D, E, F
    5, 5, 5,       # 4) G, H, I
    6, 6, 6,       # 5) J, K, L
    7, 7, 7,       # 6) M, N, O
    8, 8, 8, 8,    # 7) P, Q, R, S
    9, 9, 9,       # 8) T, U, V
    10, 10, 10, 10 # 9) W, X, Y, Z
]
sum_time = 0
for c in s:
    sum_time += dial_times[ord(c) - ord('A')]
print(sum_time)

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin','utf8').trim().split('');
const dial_times = [
    3, 3, 3,       // 2) A, B, C
    4, 4, 4,       // 3) D, E, F
    5, 5, 5,       // 4) G, H, I
    6, 6, 6,       // 5) J, K, L
    7, 7, 7,       // 6) M, N, O
    8, 8, 8, 8,    // 7) P, Q, R, S
    9, 9, 9,       // 8) T, U, V
    10, 10, 10, 10 // 9) W, X, Y, Z
];
let sum_time = 0;
input.forEach(c => {
    sum_time += dial_times[c.charCodeAt(0) - 'A'.charCodeAt(0)];
});
console.log(sum_time);

 

11번 그대로 출력하기

문제

입력받은 대로 출력하는 프로그램을 작성하시오.

 

입력

입력이 주어진다. 입력은 최대 100줄로 이루어져 있고, 알파벳 소문자, 대문자, 공백, 숫자로만 이루어져 있다. 각 줄은 100글자를 넘지 않으며, 빈 줄은 주어지지 않는다. 또, 각 줄은 공백으로 시작하지 않고, 공백으로 끝나지 않는다. 은 대로 출력하는 프로그램을 작성하시오.

 

출력

입력받은 그대로 출력한다.

 

이번엔 상당히 간단한 문제가 주어진다. 입력받은 문자를 그대로 출력해야 한다. 

 

C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    while (getline(cin, s)){
        cout << s << "\n";
    }
    return 0;
}

 

입력을 줄 단위로 구분해서 그대로 출력해야 하기 때문에 getline() 함수를 사용한다.

 

getline() 사용하면 줄 단위로 입력을 처리할 수 있다.

 

C#

using System;
class Program{
    static void Main(string[] args){
        string s;
        while ((s = Console.ReadLine()) != null){
            Console.WriteLine(s);
        }
    }
}

 

ReadLine()은 기본적으로 줄 단위로 입력받기 때문에 입력이 없을 때까지 받고 출력하고를 반복하면 된다.

 

Python

while True:
    try:
        s = input()
        if s == '':
            break
        print(s)
    except EOFError:
        break

 

입력이 없을 때 발생하는 EOFError를 처리하기 위해서 try ~ except를 사용한다.

 

Node.js

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
input.forEach(s => {
   console.log(s); 
});

 

문자열 챕터의 마지막 문제였는데 상당히 간단했다.

728x90
반응형

+ Recent posts