[백준 BOJ] 6840번 Who is in the middle? (C++/cpp)

2024. 3. 10. 13:30PS (Program Solving)/BOJ (백준)

문제 설명

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

 

6840번: Who is in the middle?

In the story Goldilocks and the Three Bears, each bear had a bowl of porridge to eat while sitting at his/her favourite chair. What the story didn’t tell us is that Goldilocks moved the bowls around on the table, so the bowls were not at the right seats

www.acmicpc.net

백준 BOJ 6840번 Who is in the middle? 문제 사진

 

접근 방법 - 중앙값 추출 연산 문제

백준의 6840번 문제는 여러 값들 사이에서 중앙값을 추출하여 정답을 구해야 하는 간단한 문제이다.

해당 문제는, 3개의 입력값들을 크기 순으로 나열하였을 때 중앙에 위치하는 숫자를 구하여 출력해야 하는 문제이다.

이 문제는 입력문 작성과 연산자 사용만 잘할 수 있다면 매우 쉽게 해결할 수 있는 문제이다.

알고리즘 문제에 대해 전무하더라도 비교 연산자와 조건문만 잘 활용할 수 있다면 아주 쉽게 정답을 구할 수 있다.

필자는 그마저도 귀찮아서 sort() 함수를 사용해서 정답을 구했다. (...)

 

문제 자체가 너무 쉽기 때문에 자세한 해설은 생략하였다.

혹여나 해당 문제를 해결하는 데에 어려움을 겪고 있다면 아래의 코드를 참고하면 도움이 될 것이다.

필자는 아래처럼 코드를 작성하여 문제를 해결하였다.

 

성공한 코드

#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable: 4996)
#include <iostream>
#include <algorithm>
#define endl '\n'
using namespace std;

//백준 6840번 코드
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);   cout.tie(NULL);
    
    int num[3];
    for (int i = 0; i < 3; i++) {
        cin >> num[i];
    }
    sort(num, num + 3);

    cout << num[1] << endl;
}

 

제출 결과

백준 BOJ 6840번 Who is in the middle? 문제 C++ 제출 결과

(2023.08.27 백준 6840번 문제 제출 결과)

반응형