Cho ba số a, b, c đầu vào. Mục tiêu: tìm giá trị/số lượng của a, b, c sau n giây với tốc độ sinh sản:
- Mỗi
abiến thànhbsau 2 giây - Mỗi
bbiến thànhcsau 5 giây - Mỗi
cbiến thành 2asau 12 giây
Hiểu qua ví dụ
Đầu vào: n_seconds = 62, a = 1, b = 1, c = 1
Đầu ra: a = 0, b = 33, c = 1
Giải thích: Sau 60s: a=32, b=0, c=0. Sau 2s nữa: a→b (b=33), b→c (c=1).
Đầu vào: n_seconds = 20, a = 1, b = 1, c = 1
Đầu ra: a = 0, b = 0, c = 6
Giải thích: Theo dõi từng giây: 2s a→b, 5s b→c, 12s c→2a, v.v. Đến 20s: a=0, b=0, c=6.
Phương pháp sử dụng
BCNN của 2, 5, 12 là 60. Thay đổi sau 60s: a=32, b=0, c=0. Sau 120s: a=32*32, b=0, c=0. Với bội số 60 tính a như công thức. Với số không phải bội, tìm bội gần nhất temp, duyệt từ temp+1 đến n_seconds áp dụng modulo 2, 5, 12.
- Nhập
a, b, c, n_seconds. - Hàm
reproduction_rate(int n_seconds, int a, int b, int c)in kết quả. temp = n_seconds / 60,a = pow(32, temp).temp = 60 * temp(bội 60 gần nhất ≤ n_seconds).- Duyệt
i = temp+1đếnn_seconds:- Nếu
i % 2 == 0:b += a, a = 0 - Nếu
i % 5 == 0:c += b, b = 0 - Nếu
i % 12 == 0:a += 2*c, c = 0
- Nếu
- In
a, b, ccuối cùng.
Ví dụ mã nguồn
#include <bits/stdc++.h>
using namespace std;
void reproduction_rate(int n_seconds, int a, int b, int c) {
int temp = n_seconds / 60;
a = (int) pow(32, temp);
temp = 60 * temp;
for (int i = temp + 1; i <= n_seconds; i++) {
if (i % 2 == 0) {
b = b + a;
a = 0;
}
if (i % 5 == 0) {
c = c + b;
b = 0;
}
if (i % 12 == 0) {
a = a + (2 * c);
c = 0;
}
}
cout << "Count of a after n seconds for given reproduction rate is: " << a << "\n";
cout << "Count of b after n seconds for given reproduction rate is: " << b << "\n";
cout << "Count of c after n seconds for given reproduction rate is: " << c;
}
int main() {
int n_seconds = 72;
int a = 2;
int b = 1;
int c = 1;
reproduction_rate(n_seconds, a, b, c);
return 0;
}
Chạy mã trên cho kết quả:
Kết quả
Count of a after n seconds for given reproduction rate is: 68 Count of b after n seconds for given reproduction rate is: 0 Count of c after n seconds for given reproduction rate is: 0