작성일 :

문제 링크

29271번 - Фильтр

설명

매일 일정량의 기름을 필터에 붓고, 넘친 기름은 버린 뒤, 남은 기름 중 일부가 시스템으로 흘러가는 과정을 n일 동안 시뮬레이션하는 문제입니다.


접근법

하루가 끝난 뒤 필터 안에 남아 있는 기름의 양만 상태로 들고 있으면 됩니다.

먼저 그날 붓는 양을 더하고, 필터 용량 r을 넘으면 r까지만 남깁니다. 그 다음 현재 기름이 x 이하이면 전부 시스템으로 흘러가고 필터는 비게 됩니다. 반대로 x보다 크면 x만 시스템으로 흘러가고 나머지는 다음 날로 넘어갑니다.

이 과정을 모든 날에 대해 반복하면서 시스템으로 흘러간 양을 누적하면 정답을 구할 수 있습니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Linq;

class Program {
  static void Main() {
    long[] first = Console.ReadLine()!.Split().Select(long.Parse).ToArray();
    int n = (int)first[0];
    long r = first[1];
    long x = first[2];

    long[] a = Console.ReadLine()!.Split().Select(long.Parse).ToArray();

    long current = 0;
    long answer = 0;

    for (int i = 0; i < n; i++) {
      current += a[i];
      if (current > r)
        current = r;

      if (current <= x) {
        answer += current;
        current = 0;
      } else {
        answer += x;
        current -= x;
      }
    }

    Console.WriteLine(answer);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  long long r, x;
  cin >> n >> r >> x;

  long long current = 0;
  long long answer = 0;

  for (int i = 0; i < n; i++) {
    long long add;
    cin >> add;

    current += add;
    if (current > r)
      current = r;

    if (current <= x) {
      answer += current;
      current = 0;
    } else {
      answer += x;
      current -= x;
    }
  }

  cout << answer << "\n";

  return 0;
}

Tags: 29271, BOJ, C#, C++, 구현, 백준, 시뮬레이션, 알고리즘

Categories: ,