[C++] 백준 5800 - 성적통계

메르센고수·2023년 8월 5일
0

Baekjoon

목록 보기
4/48
post-thumbnail

문제 - 성적통계 (Silver 5)

[백준 5800] https://www.acmicpc.net/problem/5800

접근 방식

  • max, min의 경우 C언어에서는 조건문을 통해 찾았지만, 정렬을 통해 구하면 쉽게 최댓값, 최솟값을 찾을 수 있다.
  • 또한 Largest gap의 경우도 max함수를 사용하여 구할 것이다.

소스 코드

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int N;
    cin>>N;

    for(int i=0;i<N;i++){
        int num;
        cin>>num; // 반 성적 표본의 개수
        vector<int> Score;
        for(int j=0;j<num;j++){
           int score;
           cin>>score;
           Score.push_back(score); // vector에 성적을 push
        }

        sort(Score.begin(),Score.end()); // 입력한 성적 오름차순 정렬

        int Max=Score.back(); // 정렬한 표본에서 제일 마지막이 최댓값
        int Min=Score.front(); // 정렬한 표본에서 제일 첫번째 값이 최솟값
        int gap=0;

        for(int j=1;j<num;j++){
            gap=max(gap,Score[j]-Score[j-1]);
        }
        cout<<"Class "<<i+1<<'\n';
        cout<<"Max "<<Max<<", Min "<<Min
        <<", Largest gap "<<gap<<'\n';
    }
    return 0;
}

결과

결론

C++이 C언어보다 훨씬 간결하고 편리하게 최대&최소를 구할 수 있다.

profile
블로그 이전했습니다 (https://phj6724.tistory.com/)

0개의 댓글