※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 11524번 문제인 Immortal Porpoises이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/11524 

 

11524번: Immortal Porpoises

For each data set there is a single line of output. The line consists of the data set number, K, a single space, and the number of immortal porpoise pairs alive at the end of Y years.

www.acmicpc.net

각 테스트케이스마다 N번째 피보나치 수를 1,000,000,000으로 나눈 나머지를 구하는 문제이다.

 

행렬의 거듭제곱을 이용한 빠른 점화식 연산을 이용해 문제를 해결하자.

 

아래는 제출한 소스코드이다.

#include <iostream>
using namespace std;
typedef long long ll;

ll x;

ll mat[2][2], val[2];

void solve() {
	mat[0][0] = mat[0][1] = mat[1][0] = 1, mat[1][1] = 0;
	val[0] = 1, val[1] = 0;

	while (x) {
		if (x & 1) {
			ll tmp1 = mat[0][0] * val[0] + mat[0][1] * val[1], tmp2 = mat[1][0] * val[0] + mat[1][1] * val[1];
			val[0] = tmp1 % 1000000000, val[1] = tmp2 % 1000000000;
		}
		ll tmp1 = mat[0][0] * mat[0][0] + mat[0][1] * mat[1][0], tmp2 = mat[0][0] * mat[0][1] + mat[0][1] * mat[1][1];
		ll tmp3 = mat[1][0] * mat[0][0] + mat[1][1] * mat[1][0], tmp4 = mat[1][0] * mat[0][1] + mat[1][1] * mat[1][1];
		mat[0][0] = tmp1 % 1000000000, mat[0][1] = tmp2 % 1000000000, mat[1][0] = tmp3 % 1000000000, mat[1][1] = tmp4 % 1000000000;
		x >>= 1;
	}

	cout << val[1] << '\n';
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int T; cin >> T;
	for (int t = 1; t <= T; t++) {
		cin >> x >> x;
		cout << t << ' ';
		solve();
	}
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 27327 // C++] 時間 (Hour)  (0) 2023.01.30
[BOJ 27332 // C++] 11 月 (November)  (0) 2023.01.30
[BOJ 10994 // C++] 별 찍기 - 19  (0) 2023.01.28
[BOJ 10819 // C++] 차이를 최대로  (0) 2023.01.27
[BOJ 27115 // C++] 통신소  (0) 2023.01.27

+ Recent posts