티스토리 뷰
728x90
문제 링크
https://www.acmicpc.net/problem/12888
간단해 보이니까 머리를 싸매고 잘 생각해보자..
어... 음...
헷갈린다.
이럴땐 그림판으로 그림을 그려보면 된다.
와! 규칙을 찾았다!
i가 홀수일 때 d[i]=(d[i−1]−1)∗2+1=d[i−1]∗2−1
i가 짝수일 때 d[i]=d[i−1]∗2+1
그대로 코드로 옮기면 된다.
단, 0≤n이므로 n=0인 경우도 구해줘야 한다.
답이 나올 수 있는 범위는 long long 범위인 것도 확인하자.
정답 코드
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
#include <iostream> | |
using namespace std; | |
int n; | |
long long d[63] = { 1, 1}; | |
int main() { | |
cin >> n; | |
for (int i = 2; i <= n; i++) { | |
if (i & 1) { | |
d[i] = d[i - 1] * 2 - 1; | |
} | |
else { | |
d[i] = d[i - 1] * 2 + 1; | |
} | |
} | |
cout << d[n]; | |
} |
728x90
'알고리즘 > 문제 풀이' 카테고리의 다른 글
[BOJ] 백준 1010 다리 놓기 (3) | 2018.07.09 |
---|---|
[2018 IUPC] 백준 15784 질투진서 (4) | 2018.07.05 |
[2018 IUPC] 백준 15782 Calculate! 2 (4) | 2018.06.29 |
[2018 IUPC] 백준 15781 헬멧과 조끼 (0) | 2018.06.29 |
[2018 IUPC] 백준 15780 멀티탭 충분하니? (0) | 2018.06.29 |