https://www.acmicpc.net/problem/2108
2108번: 통계학
첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. 입력되는 정수의 절댓값은 4,000을 넘지 않는다.
www.acmicpc.net
단순 구현문제다.
숫자의 범위가 -4000 ~ 4000이므로 4000만큼 오프셋을 주어서 0 ~ 8000까지의 범위로 카운팅 소트를 이용하여 문제를 해결했다.
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int num_cnt[8001];
void solution() {
int avg = 0, tmp, min_val = 1e9, max_val = -1e9;
int max_freq = 0, idx;
bool second_checked = 0;
cin >> n;
// sum, 최대, 최소값
for (int i = 0; i < n; i++) {
cin >> tmp;
avg += tmp;
++num_cnt[tmp + 4000];
min_val = min(min_val, tmp);
max_val = max(max_val, tmp);
}
// 중앙값
int mid, cnt = -1, half_n = n / 2;
for (int i = 0; i <= max_val + 4000; i++) {
cnt += num_cnt[i];
if (cnt >= half_n) {
mid = i; break;
}
}
// 최빈값
for (int i = 0; i <= max_val + 4000; i++) {
if (max_freq == num_cnt[i] && !second_checked) {
idx = i, second_checked = 1;
}
else if (max_freq < num_cnt[i]) {
max_freq = num_cnt[i], idx = i;
second_checked = 0;
}
}
idx -= 4000;
mid -= 4000;
if (avg >= 0) avg = float(avg) / n + 0.5f;
else avg = float(avg) / n - 0.5f;
cout << avg << '\n';
cout << mid << '\n';
cout << idx << '\n';
cout << max_val - min_val << '\n';
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
solution();
return 0;
}
메모리: 2052 kb | 시간: 44 ms |
'컴퓨터 사이언스 > 1고리즘' 카테고리의 다른 글
백준 4949 : 균형잡힌 세상 (0) | 2021.09.08 |
---|---|
백준 2609 : 최대공약수와 최소공배수 (0) | 2021.09.08 |
백준 1978 : 소수 찾기 (0) | 2021.09.08 |
백준 1102 : 발전소 (0) | 2021.09.08 |
백준 12015 : 가장 긴 증가하는 부분 수열 2 (0) | 2021.09.07 |