티스토리 뷰
https://www.acmicpc.net/problem/9519
9519번: 졸려
첫째 줄에 X(1 ≤ X ≤ 1,000,000,000) 가 주어지고, 둘째 줄에 X번 깜박인 후의 단어가 주어진다. 단어는 알파벳 소문자로만 이루어져 있고, 길이는 구간 [3,1000]에 포함된다.
www.acmicpc.net
풀이
1) 단어가 홀수일 경우와 짝수일 경우로 나누어 단어를 섞는다. 섞을때 마다 list에 저장한다.
2) 섞은 결과가 map에 이미 존재할 경우 루프를 돈다는 의미이다.
3) 루프를 발견하면 해당 map의 value 가 주기가 된다.
4) list.get(N을 주기로 나눈 나머지) 가 정답이 된다.
주의사항
1) String 을 더하는 방식으로 하면 오래 걸린다. StringBuilder를 사용하자.
package com.baekJoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BJ_S1_9519_졸려 {
static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
static int X;
static String word;
public static void main(String[] args) throws NumberFormatException, IOException {
input = new BufferedReader(new StringReader(src));
X = Integer.parseInt(input.readLine());
int temp = X;
word = input.readLine();
int N = word.length();
String tempString = word;
StringBuilder head = new StringBuilder();
StringBuilder tail = new StringBuilder();
Map<String, Integer> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add(word);
int cnt = 0;
while(temp>0) {
head.setLength(0);
tail.setLength(0);
if(N%2 == 0) { // 짝
for(int i=N-1; i>=0; i-=2) {
tail.append(tempString.charAt(i));
}
for(int i=0; i<N; i+=2) {
head.append(tempString.charAt(i));
}
}else { // 홀
for(int i=N-2; i>=0; i-=2) {
tail.append(tempString.charAt(i));
}
for(int i=0; i<N; i+=2) {
head.append(tempString.charAt(i));
}
}
head.append(tail);
tempString = head.toString();
list.add(tempString);
if(map.get(tempString) == null) {
map.put(tempString, cnt++);
}else {
break;
}
temp--;
}
if(temp>0) { // 주기를 발견할 경우
temp = X % cnt;
System.out.println(list.get(temp));
}else {
System.out.println(tempString);
}
}
static String src =
"11\r\n" +
"srama";
}
후기
조금 머리를 쓰게한 문제이다. String을 합치는 것, 루프를 어떻게 찾을지, 루프를 찾을경우 정답을 어떻게 얻을지 하나하나가 의미있는 좋은 문제였다.
'Algorithm' 카테고리의 다른 글
[백준] S1 13335 트럭 (java) (0) | 2021.07.30 |
---|---|
[백준] S1 1052 물병 (java) (0) | 2021.07.30 |
[백준] S1 19638 센티와 마법의 뿅망치 (java) (0) | 2021.07.29 |
[백준] S1 20923 숫자 할리갈리 게임 (java) (0) | 2021.07.29 |
[백준] S1 3258 컴포트 (java) (0) | 2021.07.29 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 알고리즘
- 구현
- 자바
- 다익스트라
- 백트래킹
- react native
- PriorityQueue
- map
- DFS
- 코딩새내기
- 리액트
- G5
- 객체지향
- SWEA
- Spring Boot
- react
- BFS
- java
- 우선순위큐
- 현꾸라지
- g4
- Spring
- 리액트 네이티브
- laugh4mile
- 시뮬레이션
- 문자열
- S2
- 백준
- 그리디
- S3
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함