[Codeforces] #2148A - Sublime Sequence [Java][C++]
[Codeforces] #2148A - Sublime Sequence [Java][C++]
1. 문제 풀이
$x$ 와 $n$ 이 주어졌을 때, 수열은 $x$, $-x$, $x$, $\ldots$ 와 같이 $x$ 의 부호가 바뀐 것이 $n$ 번 반복된다. 이때 수열의 합을 구하는 문제로 두 항마다 합이 $0$ 이 되므로 $n$ 이 짝수면 수열의 합은 $0$ 이 되며, $n$ 이 홀수면 수열의 합이 $x$ 가 된다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= t; tc++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
if (n % 2 == 0) {
sb.append("0\n");
} else {
sb.append(x).append("\n");
}
}
System.out.println(sb);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
int x, n;
cin >> x >> n;
if (n % 2 == 0) {
cout << '0' << '\n';
} else {
cout << x << '\n';
}
}
}
This post is licensed under CC BY 4.0 by the author.