천천히 빛나는

백준 단계 4 : 1차원 배열 (C++) 본문

C++/BAEKJOON (C++)

백준 단계 4 : 1차원 배열 (C++)

까만콩 •ᴥ• 2023. 8. 18. 01:56

10807. 총 N개의 정수가 주어졌을 때, 정수 v가 몇 개인지 구하는 프로그램을 작성하시오.

#include<iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, v;
    cin >> n;
    int* arr = new int[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    cin >> v;
    int count = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == v)
        {
            count++;
        }
    }
    cout << count;
    return 0;

}

동적할당을 사용하여 계산하였다.

 

 

10871. 정수 N개로 이루어진 수열 A와 정수 X가 주어진다. 이때, A에서 X보다 작은 수를 모두 출력하는 프로그램을 작성하시오.

#include<iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, x;
    cin >> n >> x;
    int* a = new int[n];
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i < n; i++) {
        if (a[i] < x)
            cout << a[i] << " ";
    }
    return 0;
}

동적할당으로 배열을 만들어주지 않아도 된다. 예를 들어 a[10000];로 10000칸의 배열을 생성해주어도 된다.

 

 

10818. N개의 정수가 주어진다. 이때, 최솟값과 최댓값을 구하는 프로그램을 작성하시오.

#include<iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    int* arr = new int[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int min = arr[0], max = arr[0];
    for (int i = 1; i < n; i++)
    {
        if (min > arr[i])
            min = arr[i];
        if (max < arr[i])
            max = arr[i];
    }
    cout << min << " " << max;
    return 0;
}

직접 비교해서 min과 max를 계산하는 방식이다. 사실 이 방식에서는 배열을 굳이 사용하지 않아도 된다.

minValue = min(minValue, inputValue);
minValue = max(minValue, inputValue);

이와 같이 algorithm의 min, max 함수를 사용할 수도 있다. (if 문 대신에)

 

sort(배열의 시작주소, 배열의 마지막주소);

배열의 정렬(sort 함수)을 사용하면 보다 간단하게 코드를 작성할 수 있다. c++의 배열과 포인트를 안다면 알 수 있지만, 배열 arr를 선언하고 arr을 출력해보면 arr[0]의 주소값이 된다. 즉 sort(array, array + n); 로 작성하면 되는 것이다.

sort(arr, arr + n);
cout << arr[0] << " " << arr[n - 1];

이와 같이 cin 이후에 간단하게 출력이 가능하다

 

 

2562. 이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.

#include <iostream>
using namespace std;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int x, max = 0, maxIndex=0;
    for(int i = 1; i <= 9; i++){
        cin >> x;
        if (x > max){
            max = x;
            maxIndex = i;
        }    
    }
    cout << max << '\n' << maxIndex;
    return 0;    
}

배열을 정렬시키는 방식으로 쓸 수 없다. 배열로 입력받고 index를 찾는 방식으로 for문을 구성해도 되지만 배열을 이용하지 않고 코드를 작성해보았다.

 

 

10810. 공을 어떻게 넣을지가 주어졌을 때, M번 공을 넣은 이후에 각 바구니에 어떤 공이 들어 있는지 구하는 프로그램을 작성하시오.

#include <iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    int i, j, k;
    int basket[101] = { 0 };
    for (int p = 0; p < m; p++) {
        cin >> i >> j >> k;
        for (int q = i; q <= j; q++) {
            basket[q] = k;
        }
    }
    for (int p = 1; p <= n; p++)
    {
        cout << basket[p] << " ";
    }
    return 0;
}

동적할당으로 배열을 생성해도 되지만 이번에는 일반 배열을 만들어서 작성해보았다.

 

 

10813. 공을 어떻게 바꿀지가 주어졌을 때, M번 공을 바꾼 이후에 각 바구니에 어떤 공이 들어있는지 구하는 프로그램을 작성하시오.

#include<iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    int basket[101];
    for (int t = 1; t <= n; t++) {
        basket[t] = t;
    }
    int i, j;
    for (int t = 0; t < m; t++) {
        cin >> i >> j;
        int temp = basket[i];
        basket[i] = basket[j];
        basket[j] = temp;
    }
    for (int t = 1; t <= n; t++) {
        cout << basket[t] << " ";
    }
    return 0;
}

 algorithm의 swap 함수를 사용하여 swap 부분을 구현할 수도 있다.

for (int t = 0; t < m; t++) {
    cin >> i >> j;
    swap(basket[i], basket[j]);
}

#include<algorithm>을 해주어야 하는 것을 잊지 말아야 한다.

 

<<algorithm헤더의 유용한 함수들>>

1) sort 함수 : 오름차순 정렬 (1, 2, 3, 4 ...)

int a[10] = { 9,3,5,4,1,10,8,6,7,2 };
sort(a, a + 10); // 오름차순
sort(a, a + 10, greater<int>()); // 내림차순

2) 최대값, 최소값 구하기 : max_element, min_element

int a[10] = { 9,3,5,4,1,10,8,6,7,2 };
cout << *max_element(a, a + 10) << endl;

3) 값 바꾸기 : swap

swap(a, b);

 

 

5597. 교수님이 내준 특별과제를 28명이 제출했는데, 그 중에서 제출 안 한 학생 2명의 출석번호를 구하는 프로그램을 작성하시오.

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    bool student[31] = { 0 };
    int n;
    for (int i = 0; i < 28; i++)
    {
        cin >> n;
        student[n] = 1;
    }
    for (int i = 1; i <= 30; i++)
    {
        if (student[i] == false) {
            cout << i << "\n";
        }
    }
    return 0;
}

배열을 사용하여 구현하였다.

 

 

3052. 수 10개를 입력받은 뒤, 이를 42로 나눈 나머지를 구한다. 그 다음 서로 다른 값이 몇 개 있는지 출력하는 프로그램을 작성하시오.

#include<iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int x;
    bool r[42] = { 0 };
    int count = 0;
    for (int i = 0; i < 10; i++)
    {
        cin >> x;
        if (r[(x % 42)] != 1){
            r[(x % 42)] = 1;
            count++;
        }
    }
    cout << count;
    return 0;
}

%을 이용한 간단한 문제이다

 

 

10811. 바구니의 순서를 어떻게 바꿀지 주어졌을 때, M번 바구니의 순서를 역순으로 만든 다음, 바구니에 적혀있는 번호를 가장 왼쪽 바구니부터 출력하는 프로그램을 작성하시오

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    int i, j;
    int b[101] = {};

    for (int t = 1; t <= n; t++)
    {
        b[t] = t;
    }

    for (int t = 0; t < m; t++)
    {
        cin >> i >> j;
        while(j > i)
        {
            swap(b[i], b[j]);
            j--;
            i++;
        }
    }
    for (int t = 1; t <= n; t++)
    {
        cout << b[t] << " ";
    }
    return 0;
}

swap을 사용하였다. 

for (int t = 0; t <= (j - i) / 2; t++)
{
   swap(a[t + i], a[j - t]);
}

이와 같이 for문으로 구현할 수도 있다.

 

int a[] = { 4, 5, 6, 7 };
reverse(begin(a), end(a))

algorithm의 reverse 함수를 사용할 수도 있다. begin과 end도 함수이다.

int a[] = { 4, 5, 6, 7 };
reverse(a, a+2);

// {5, 4, 6, 7} 로 됨

a부터 a+1까지 swap 하라는 뜻이 된다. 여기서 a는 4이고 a+1은 5가 있는 주소가 된다.

 

 

1546. 세준이의 성적을 위의 방법대로 새로 계산했을 때, 새로운 평균을 구하는 프로그램을 작성하시오.

#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    double sum = 0;
    double grade[1000];
    for (int i = 0; i < n; i++)
    {
        cin >> grade[i];
    }
    double m = *max_element(begin(grade), end(grade));
    for (int i = 0; i < n; i++)
    {
        sum += (100 * grade[i]) / m;
    }
    cout << sum / n;
    return 0;
}

 

sort로 배열의 오름차순 정리를 하면 가장 마지막에 max 이므로 굳이 max_element 함수를 사용하지 않아도 된다. 매열을 쓰지 않고도 풀 수 있으나 펼 차이는 없다. 코드 길이가 더 길어질 뿐이다.

cout << fixed;
cout.precision(20);

소수점 관련 사항이 있길래 소수점 자리를 고정하는 코드를 다시 한번 작성해보았다.