728x90
문제 링크: https://www.acmicpc.net/problem/16208
16208번: 귀찮음
현우는 무슨 이유에선지 길이 a1, ..., an의, 총 n개의 쇠막대가 필요해졌다. 하지만 그가 가진 것은 길이 a1+...+an의 하나의 쇠막대뿐이었다. 현우는 이 막대를 직접 잘라서 원래 필요하던 n개의 쇠
www.acmicpc.net
문제 풀이
쉽고 쉬운 그리디 문제. xy의 값이 작을수록 값이 작아지기 때문에 막대기의 총합을 구하고 정렬을 한 후 첫번째 막대부터 차례로 총합에서 빼고 곱해주면 된다. 즉 x가 막대 1개, y가 x를 제외한 합이라고 생각하면 된다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n = int(input()) | |
steel = sorted(list(map(int, input().split()))) | |
ans = 0 | |
s = sum(steel) | |
for i in range(n): | |
s -= steel[i] | |
ans += steel[i] * s | |
print(ans) |
파이썬 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
using namespace std; | |
int main() { | |
long long n, x, sum = 0, ans = 0; | |
vector<int> steel; | |
cin >> n; | |
for (int i = 0; i < n; i++){ | |
cin >> x; | |
sum += x; | |
steel.push_back(x); | |
} | |
for (int i = 0; i < n; i++){ | |
sum -= steel[i]; | |
ans += steel[i]*sum; | |
} | |
cout << ans << '\n'; | |
} |
C++ 코드
728x90
'BOJ' 카테고리의 다른 글
[BOJ][Python][C++] 백준 24417번 - 알고리즘 수업 - 피보나치 수 2 (0) | 2022.04.05 |
---|---|
[BOJ][Python] 백준 1312번 - 소수 (0) | 2022.04.05 |
[BOJ][Text] 백준 24905번 - 24905번 문제 (0) | 2022.04.03 |
[BOJ][Text] 백준 24904번 - Baekjoon Wordline Judge (0) | 2022.04.03 |
[BOJ][Text] 백준 24900번 - 한별 찍기 (0) | 2022.04.03 |