본문 바로가기

알고리즘/BOJ

[Python&C++]1026-보물

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

 

1026번: 보물

첫째 줄에 N이 주어진다. 둘째 줄에는 A에 있는 N개의 수가 순서대로 주어지고, 셋째 줄에는 B에 있는 수가 순서대로 주어진다. N은 50보다 작거나 같은 자연수이고, A와 B의 각 원소는 100보다 작거�

www.acmicpc.net

A의 순서를 출력할 필요가 없기때문에, 사실 B도 재배열 해도 된다.

그래서, A를 오름차순, B를 내림차순으로 정렬해서, 간단하게 구현했다.

Python

_ = input()
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
a.sort()
b.sort(reverse = True)
result = 0
for i in range(len(b)):
    result += a[i]*b[i]
print(result)

C++

#include <iostream>
#include <algorithm>

bool calc(int a, int b)
{
    return a>b;
}

int main()
{
    int a[50], b[50], len, c, result = 0;
    std::cin >> len;
    for(int i = 0; i < len; i++)
    {
        std::cin >> c;
        a[i] = c;
    }
    for(int i = 0; i < len; i++)
    {
        std::cin >> c;
        b[i] = c;
    }
    std::sort(a, a+len);
    std::sort(b, b+len, calc);
    for(int i = 0; i < len; i++)
    {
        result += a[i]*b[i];
    }
    std::cout << result;
}

'알고리즘 > BOJ' 카테고리의 다른 글

[Python]16489-삼각형 해커  (0) 2020.09.10
[Python]1194-달이 차오른다, 가자.  (0) 2020.08.10
[Python&C++]7868-해밍 수열  (0) 2020.07.11
[Python&C++]1037-약수  (0) 2020.05.19
[Python&C++]1032-명령 프롬포트  (0) 2020.05.18
[Python&C++]1004-어린 왕자  (0) 2020.05.18
[Python&C++]1003-피보나치 함수  (0) 2020.05.18
[Python&C++]1002-터렛  (0) 2020.05.18