본문 바로가기

PS/BOJ

[C++] BOJ (백준) 10250 : ACM 호텔

문제

10250번: ACM 호텔 (acmicpc.net)

 

10250번: ACM 호텔

프로그램은 표준 입력에서 입력 데이터를 받는다. 프로그램의 입력은 T 개의 테스트 데이터로 이루어져 있는데 T 는 입력의 맨 첫 줄에 주어진다. 각 테스트 데이터는 한 행으로서 H, W, N, 세 정수

www.acmicpc.net

코드 1 (브루트포스)
#include <iostream>

using namespace std;

void solve(int h, int n) {
  int floor = 0;
  int room = 1;
  while (n--) {
    if (floor < h) floor++;
    else {
      floor = 1;
      room++;
    }
  }
  printf("%d%02d\n", floor, room);
}

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

  int t;
  cin >> t;
  while (t--) {
    int h, w, n;
    cin >> h >> w >> n;
    solve(h, n);
  }
  return 0;
}
설명

그냥 브루트포스로 풀어도 0ms로 풀린다.
사실 이 문제에서 입력으로 방 배정이 불가능한 경우가 주어지지 않기 때문에 w는 필요 없다.

 

코드 2 (수학)
#include <iostream>

using namespace std;

void solve(int h, int n) {
  int floor = (n - 1) % h + 1;
  int room = (n - 1) / h + 1;
  printf("%d%02d\n", floor, room);
}

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

  int t;
  cin >> t;
  while (t--) {
    int h, w, n;
    cin >> h >> w >> n;
    solve(h, n);
  }
  return 0;
}
설명

규칙을 찾기 위해 h가 3인 경우를 보자.
n = 1 : 101
n = 2 : 201
n = 3 : 301
n = 4 : 102
n = 5 : 202
n = 6 : 302
n = 7 : 103
n = 8 : 203
n = 9 : 303

답이 YYXX 형태일 때 YY를 floor, XX를 room이라고 하면
room은 3(h)의 배수 단위로 바뀌는 것을 확인할 수 있다.
공식을 만들면 room = (n - 1) / h + 1 이다.
floor는 반대로 3(h)의 배수의 주기성을 가진다.
공식을 만들면 floor = (n - 1) % h + 1 이다.

'PS > BOJ' 카테고리의 다른 글