[C++] BAEKJOON 2108


統計学


質問する


処理数は統計学においてかなり重要なことである.統計学では、N個の数を表す基本統計値は以下のとおりである.しかし、Nは奇数であると仮定する.
算術平均:N個の数の和をNで割った値
中心値:N個の数字が順次に出たときの中央にある値.
最も頻繁な値:N個の数字の中で最も多い値を表示します
範囲:N個の数字の中で最も高い値と最も高い値の差
N個の数値が与えられた場合、4つのデフォルト統計値を求めるプログラムを作成します.

入力


第1行は数N(1≦N≦500000)を与える.次のN行には整数があります.入力した整数のセクション値は4000を超えません.

しゅつりょく


1行目は算術平均数を出力します.小数点以下の1位に四捨五入した値を出力します.
2行目は中央値を出力します.
3行目は最NULL値を出力します.複数ある場合、出力の最小値は最も頻繁な値の2番目です.
4行目の出力範囲.

コード#コード#

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

int coordinate[500001];
int cnt[8001];
int N, a, b, c, d;
int sum = 0;

int main()
{
	cin.tie(NULL); ios::sync_with_stdio(false);
	cin >> N;

	for (int i = 0; i < N; i++)
	{
		cin >> coordinate[i];
		sum += coordinate[i];
		cnt[coordinate[i]+4000]++;
	}
	
	sort(coordinate, coordinate + N);
	
	int flag;
	int max = 0;
	
	for (int i = 0; i < 8001; i++)
	{
		if (cnt[i] > max)
		{
			max = cnt[i];
			flag = i;
		}
	}

	for (int i = flag + 1; i < 8001; i++)
	{
		if (cnt[i] == max)
		{
			flag = i;
			break;
		}
	}

	a = round(double(sum) / N);
	b = coordinate[(N - 1) / 2];
	c = flag - 4000;
	d = coordinate[N - 1] - coordinate[0];

	cout << a << "\n";
	cout << b << "\n";
	cout << c << "\n";
	cout << d << "\n";
}
#define _CRT_SECURE_NO_WARNINGS
#include<vector>
#include<algorithm>
#include<math.h>
#include <cstdio>
using namespace std;

bool sorting(const vector<int>& a, const vector<int> b) {
    if (a[1] > b[1]) {
        return true;
    }
    else if (a[1] == b[1]) {
        return a[0] < b[0];
    }
    else {
        return false;
    }
}
int main(void) {

    vector<int> arr;
    vector<vector<int>> count(8001, vector<int>(2, 0));
    int N, input;
    int i, j, cntP, cntQ;
    int sum, mid, max, range;
    double avg;
    int same = 0;

    scanf("%d", &N);
    sum = 0;
    mid = N / 2;
    max = 0;

    for (i = 0; i < N; i++) {
        scanf("%d", &input);
        arr.push_back(input);
        sum += input;
        count[input + 4000][0] = input;
        count[input + 4000][1]++;
    }
    avg = double(sum) / double(N);
    sum = round(avg);
    sort(arr.begin(), arr.end());
    sort(count.begin(), count.end(), sorting);

    for (i = 1; i < count.size(); i++) {
        cntQ = count[i - 1][1];
        cntP = count[i][1];
        
        if (cntQ == 0) { break; }
        if (cntQ > cntP) { 
            max = count[i - 1][0];
            break;
        }
        else if (same == 0) {
            max = count[i][0];
            same++;
        }
        else {
            break;
        }
        
    }

    printf("%d\n", sum);
    printf("%d\n", arr[mid]);
    printf("%d\n", max);
    printf("%d\n", arr[arr.size() - 1] - arr[0]);

    return 0;
}

ソース


+> https://cocoon1787.tistory.com/157