(x, 0)과 (x, 1 + 2 + … + x)를 잇는 두 막대들에 대해서 y<k 인 막대가 지워진 후의 막대의 길이가 주어질 때 양의 정수인 k의 값을 구하는 문제이다. 두 막대는 x 좌표가 1 차이다.
두 막대의 원래 길이는 x*(x+1) / 2 이고 두 막대의 길이의 차이가 두 막대의 x좌표의 차이가 1이므로 높이의 차이가 긴 막대의 길이이다. 즉 원래 긴 막대의 길이는 두 막대의 길이의 차 * (차 + 1) / 2 가 되고 k는 이 값 - 주어진 긴 막대의 길이가 된다.
long a = Long.parseLong(st.nextToken()), b = Long.parseLong(st.nextToken());
long diff = b - a;
long realB = (diff*(diff+1)) / 2;
sb.append(realB - b).append('\n');
결과 코드는 다음과 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for(int tc=1; tc<=T; tc++) {
sb.append('#').append(tc).append(' ');
StringTokenizer st = new StringTokenizer(br.readLine());
long a = Long.parseLong(st.nextToken()), b = Long.parseLong(st.nextToken());
long diff = b - a;
long realB = (diff*(diff+1)) / 2;
sb.append(realB - b).append('\n');
}
br.close();
System.out.print(sb);
}
}'알고리즘(백준 등) 공부' 카테고리의 다른 글
| SWEA 12369. 일련번호 붙이기 (0) | 2026.05.22 |
|---|---|
| SWEA 12741. 두 전구 (0) | 2026.05.21 |
| SWEA 13041. 게으름뱅이 왕국 (0) | 2026.05.20 |
| SWEA 13218. 조별과제 (0) | 2026.05.19 |
| SWEA 13219. 진행률 (0) | 2026.05.19 |