작성일 :

문제 링크

1302번 - 베스트셀러

설명

오늘 판매된 책 제목들이 주어질 때, 가장 많이 팔린 책의 제목을 출력하는 문제입니다. 가장 많이 팔린 책이 여러 권이면 사전 순으로 가장 앞서는 제목을 출력해야 합니다.


접근법

제목을 하나씩 입력받으면서, 같은 제목이 이미 등장했다면 해당 제목의 판매 횟수를 1 증가시키고 처음 등장한 제목이라면 1로 저장합니다.

이후 모든 제목을 확인하면서 가장 큰 판매 횟수를 찾고, 판매 횟수가 같다면 문자열을 사전 순으로 비교해 더 앞서는 제목을 선택하면 됩니다.



Code

C#

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
using System;
using System.Collections.Generic;

class Program {
  static void Main() {
    int n = int.Parse(Console.ReadLine()!);
    var count = new Dictionary<string, int>();

    for (int i = 0; i < n; i++) {
      string title = Console.ReadLine()!;
      if (count.ContainsKey(title))
        count[title]++;
      else
        count[title] = 1;
    }

    string answer = "";
    int best = -1;

    foreach (var item in count) {
      if (item.Value > best) {
        best = item.Value;
        answer = item.Key;
      } else if (item.Value == best && string.CompareOrdinal(item.Key, answer) < 0) {
        answer = item.Key;
      }
    }

    Console.WriteLine(answer);
  }
}

C++

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
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  cin >> n;

  map<string, int> count;
  for (int i = 0; i < n; i++) {
    string title;
    cin >> title;
    count[title]++;
  }

  string answer;
  int best = -1;

  for (auto& item : count) {
    if (item.second > best) {
      best = item.second;
      answer = item.first;
    }
  }

  cout << answer << "\n";

  return 0;
}

Tags: 1302, BOJ, C#, C++, 문자열, 백준, 알고리즘, 자료 구조

Categories: ,