본문 바로가기

Algorithm/Implementation

(C++) - 백준(BOJ) 4850 : Baskets of Gold Coins

반응형

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

 

4850번: Baskets of Gold Coins

The input file will consist of one or more lines; each line will contain data for one instance of the problem. More specifically, each line will contain four positive integers, separated by one blank space. The first three integers are, respectively, the n

www.acmicpc.net

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

바구니의 개수 N, 동전 한 개의 무개 w, 가벼운 동전과 기존 동전의 무게 차이 d, 고른 동전들의 전체 무게 sum을 선언하고 EOF인 동안 입력받습니다.

📔 풀이과정

답은 두 가지로 나뉩니다.

sum = 1*w + 2*w + 3*w + ... + (N-1)*w 이므로

1. 1 ~ N-1번 바구니 중 가벼운 동전이 없을 때

 sum = N*(N-1)/2*w

2. 있을 때

 sum = N*(N-1)/2*w- x*d (x는 바구니의 번호)

 

N*(N-1)/2*w의 값는 지역변수 fullWeight를 선언해 저장합니다.

x = (sum - fullWeight) / d가 답이므로 지역변수 ans를 선언 후 값을 저장합니다.

 

* N번째 바구니가 가벼운 동전을 포함할 수도 있습니다.

📔 정답출력

ans를 출력해줍니다.


📕 Code

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll N, w, d, sum;
int main(){
    while(cin >> N >> w >> d >> sum){
        ll fullWeight = N * (N - 1) / 2 * w;
        ll ans = (sum - fullWeight) / d;
        if(!ans) cout << N << '\n';
        else cout << ans << '\n';
    }
}