규칙을 찾는 문제로써 표를 통해 1부터 20까지의 예를 나타내 보았다.
여기서 작동 횟수가 1씩 커지는 것이 2번에 걸처 반복되면 반복 횟수(즉, 차이가 1씩 증가하는 횟수의 그룹)도 1씩 증가하는 것을 볼 수 있다.
이것을 코딩해봤는데 계속 시간 초과가 뜬다..
시간 초과된 코드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args){ | |
Scanner sc = new Scanner(System.in); | |
int cnt = Integer.parseInt(sc.nextLine()); | |
int df = 2; | |
int flag = 0; | |
int inc = 0; | |
int x=2; | |
int result=3; | |
for(int i=0; i<cnt; i++) { | |
int a = sc.nextInt(); | |
int b = sc.nextInt(); | |
int df2 = b-a; | |
while(df2>df) { | |
if(x==inc) { | |
if(flag==1) { | |
result++; | |
x = inc+1; | |
inc=0; | |
flag=0; | |
}else{ | |
result++; | |
flag=1; | |
inc=0; | |
} | |
} | |
df++; | |
inc++; | |
} | |
System.out.println(result); | |
df=2; | |
flag=0; | |
inc=0; | |
x=2; | |
result=3; | |
} | |
sc.close(); | |
} | |
} |
다음은 더 간단히 만든 코드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Main{ | |
public static void main(String args[]){ | |
Scanner sc = new Scanner(System.in); | |
int cnt = Integer.parseInt(sc.nextLine()); | |
for(int i=0; i<cnt; i++) { | |
int a = sc.nextInt(); | |
int b = sc.nextInt(); | |
int dis = b-a; | |
int x = 0; | |
int result = 1; | |
while(x<dis) { | |
result++; | |
x+=(result/2); | |
} | |
System.out.println(result-1); | |
} | |
} | |
} |
계속 시간 초과가 뜨는데 더 좋은 방법을 알고계신분은 댓글로 남겨주세요...
'백준 알고리즘 > JAVA' 카테고리의 다른 글
[JAVA 자바] 백준 5622번 다이얼 (0) | 2018.07.12 |
---|---|
[JAVA 자바] 백준 2908번 상수 (0) | 2018.07.12 |
[JAVA 자바] 백준 1316번 그룹 단어 체커 (0) | 2018.07.11 |
[JAVA 자바] 백준 1193번 분수찾기 (0) | 2018.07.11 |
[JAVA 자바] 백준 2292번 벌집 (0) | 2018.07.10 |