Life Engineering
[SWEA 5604] 구간 합 (Java) 본문
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWXGGNB6cnEDFAUo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution_SWEA_5604 {
static int T;
static long A, B;
static long[] numbers;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=null;
T=Integer.parseInt(br.readLine());
for (int t=1; t<=T; t++) {
st=new StringTokenizer(br.readLine());
A=Long.parseLong(st.nextToken());
B=Long.parseLong(st.nextToken());
long mul=1;
numbers=new long[10];
while (A<=B) {
while (B%10!=9 && A<=B) {
calc(B, mul);
B--;
}
if (A>B) break;
while (A%10!=0 && A<=B) {
calc(A, mul);
A++;
}
A/=10;
B/=10;
for (int i=0; i<10; i++) {
numbers[i]+=((B-A+1)*mul);
}
mul*=10;
}
long answer=0;
for (int i=0; i<10; i++) {
answer+=(i*numbers[i]);
}
System.out.println("#"+t+" "+answer);
}
}
private static void calc(long n, long mul) {
long temp=n;
while (temp>0) {
numbers[(int)(temp%10L)]+=(mul);
temp/=10;
}
}
}
어려워서 힌트보고 풀었다..
개인적으로 https://www.slideshare.net/Baekjoon/baekjoon-online-judge-1019 (백준 1019번 풀이) 가 도움이 많이 되었다
이 문제의 포인트는 두개의 숫자 끝자리가 각각 0, 9일때 어떤지를 관찰해서, 이 법칙을 이용해
A, B 끝자리를 0, 9로 만들어 준 후 나타난 숫자의 횟수를 저장해 준다는 점이다.
그리고 자릿수별로 나타난 숫자의 횟수를 계산해주는 점을 잊지 말자.
'Problem Solving' 카테고리의 다른 글
[BOJ 21611] 마법사 상어와 블리자드 (Java) (0) | 2022.04.13 |
---|---|
[SWEA 4013] 특이한 자석 (Java) (0) | 2022.04.13 |
[SWEA 9760] Poker Game (Java) (0) | 2022.04.12 |
[BOJ 11049] 행렬 곱셈 순서 (Java) (0) | 2022.04.11 |
[BOJ 20058] 마법사 상어와 파이어스톰 (Java) (0) | 2022.04.11 |