작성일 :

문제 링크

7181번 - Mõttemeister

설명

4자리 비밀 숫자와 여러 추측이 주어질 때, 각 추측에 대해 비밀 숫자에 존재하는 숫자의 개수와 자리까지 일치하는 개수를 구하는 문제입니다.

중복된 숫자는 비밀에 등장하는 횟수만큼만 인정합니다.


접근법

각 추측마다 비밀과 추측의 숫자 빈도를 세어 각 숫자별 최솟값의 합을 구합니다.

이후 같은 위치에서 일치하는 숫자의 개수를 세어 출력합니다.


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
using System;

class Program {
  static void Main() {
    var secret = Console.ReadLine()!;
    var n = int.Parse(Console.ReadLine()!);

    for (var i = 0; i < n; i++) {
      var guess = Console.ReadLine()!;

      var sCnt = new int[10];
      var gCnt = new int[10];
      foreach (var c in secret)
        sCnt[c - '0']++;
      foreach (var c in guess)
        gCnt[c - '0']++;

      var a = 0;
      var b = 0;
      for (var d = 0; d < 10; d++) a += Math.Min(sCnt[d], gCnt[d]);
      for (var k = 0; k < 4; k++) if (secret[k] == guess[k]) b++;

      Console.WriteLine($"{a} {b}");
    }
  }
}

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

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

  string secret; cin >> secret;
  int n; cin >> n;

  while (n--) {
    string guess; cin >> guess;

    int sCnt[10] = {0}, gCnt[10] = {0};
    for (char c : secret) sCnt[c - '0']++;
    for (char c : guess) gCnt[c - '0']++;

    int a = 0, b = 0;
    for (int d = 0; d < 10; d++)
      a += min(sCnt[d], gCnt[d]);
    for (int i = 0; i < 4; i++) {
      if (secret[i] == guess[i]) b++;
    }

    cout << a << " " << b << "\n";
  }

  return 0;
}

Tags: 7181, BOJ, C#, C++, 구현, 백준, 알고리즘

Categories: ,