[백준 17944] 퐁당퐁당 1 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
팔 개수가 1에서 2n까지 증가한 뒤 다시 1까지 감소하는 패턴이 반복될 때, t번째 차례의 팔 개수를 구하는 문제입니다.
접근법
한 주기의 길이는 증가 구간 2n개와 감소 구간 2n - 2개를 합친 4n - 2입니다.
먼저 t - 1을 주기로 나눈 나머지로 주기 내 위치를 구합니다.
위치가 2n 미만이면 증가 구간이므로 위치 + 1이 답이고, 그렇지 않으면 감소 구간이므로 4n - 위치 - 1이 답입니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
class Program {
static void Main() {
var parts = Array.ConvertAll(Console.ReadLine()!.Split(), long.Parse);
var n = parts[0];
var t = parts[1];
var len = 4 * n - 2;
var idx = (t - 1) % len;
var ans = (idx < 2 * n) ? (idx + 1) : (4 * n - (idx + 1));
Console.WriteLine(ans);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll n, t; cin >> n >> t;
ll len = 4 * n - 2;
ll idx = (t - 1) % len;
ll ans = (idx < 2 * n) ? (idx + 1) : (4 * n - (idx + 1));
cout << ans << "\n";
return 0;
}