[백준 27325] 3つの箱 (Three Boxes) (C#, C++) - soo:bak
작성일 :
문제 링크
설명
공이 박스 1에서 시작하여 L/R 명령에 따라 이동할 때, 박스 3에 들어간 횟수를 세는 문제입니다.
L은 왼쪽으로, R은 오른쪽으로 이동하며, 박스 번호는 1에서 3 사이를 벗어나지 않습니다.
접근법
박스가 3개뿐이므로 현재 위치를 정수로 관리하면서 명령을 순서대로 처리합니다.
L이면 위치를 1 감소시키되 1 미만이 되지 않도록 하고, R이면 1 증가시키되 3을 초과하지 않도록 합니다.
매 이동 후 위치가 3이면 횟수를 증가시킵니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
class Program {
static void Main() {
var n = int.Parse(Console.ReadLine()!);
var s = Console.ReadLine()!;
var pos = 1;
var cnt = 0;
foreach (var c in s) {
if (c == 'L') pos = Math.Max(1, pos - 1);
else if (c == 'R') pos = Math.Min(3, pos + 1);
if (pos == 3) cnt++;
}
Console.WriteLine(cnt);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
string s; cin >> s;
int pos = 1;
int cnt = 0;
for (char c : s) {
if (c == 'L') pos = max(1, pos - 1);
else if (c == 'R') pos = min(3, pos + 1);
if (pos == 3) cnt++;
}
cout << cnt << "\n";
return 0;
}