题意
给出一个只含有{a, b}两种字符的串,每次扩展就用ab把串中的b给替换掉,同时用b把a给替换掉;然后给出第n次扩展后的串长为x,第m次扩展后的串长为y,求第k次扩展后的串长为多少?
思路
首先简单的扩展几个串可以发现,a的个数和b的个数都是fibonacci数,且按照fibonacci数数增长;
这样我们假设一开始由p个a,q个b;然后求出第n次和第m次的fibonacci数,这样就得到了一个二元一次方程组,解出来判断下就好了;
串有个最短的情况就是开始只有一个字符a;
题目中要求串的长度在 109 内;
typedef struct matrix {
long long v[2][2];
matrix() {memset(v, 0, sizeof v);}
}matrix;
long long dp[100];
long long top;
void init() {
dp[0] = 0;dp[1] = 1;
for (int i = 2;;++i) {
dp[i] = dp[i-1] + dp[i-2];
top = i;
if (dp[i] >= 1e9) break;
}
}
bool flag;
matrix mul(matrix a, matrix b) {
matrix c;
for (int i = 0;i < 2;++i) {
for (int j = 0;j < 2;++j) {
for (int k = 0;k < 2;++k) {
c.v[i][j] = c.v[i][j] + a.v[i][k] * b.v[k][j];
if (c.v[i][j] >= MOD) {
c.v[i][j] %= MOD;
flag = true;
// 判断长度是否超出了范围
}
}
}
}
return c;
}
matrix pow_mod(matrix e, long long t) {
matrix ans;
ans.v[0][0] = ans.v[1][1] = 1;
while(t) {
if (t & 1) ans = mul(ans, e);
e = mul(e, e);
t >>= 1;
}
return ans;
}
int main(int argc, const char * argv[])
{
// freopen("/Users/jamesqi/Desktop/in.txt","r",stdin);
// freopen("/Users/jamesqi/Desktop/out.txt","w",stdout);
// ios::sync_with_stdio(false);
// cout.sync_with_stdio(false);
// cin.sync_with_stdio(false);
init();
int kase;cin >> kase;
while(kase--) {
flag = false;
int n, x, m, y, k;
cin >> n >> x >> m >> y >> k;
if (n > m) {
swap(n, m);swap(x, y);
}
cout << "Case " << ++nCase << ": ";
if (y < x || m >= top || x < dp[n] || y < dp[m]) {
cout << "Impossible" << endl;
continue;
}
matrix e;
e.v[0][0] = 0;e.v[0][1] = e.v[1][0] = e.v[1][1] = 1;
matrix t1 = pow_mod(e, n - 1);
matrix t2 = pow_mod(e, m - 1);
long long a, b, c, d;
a = t1.v[0][0] + t1.v[1][0];
b = t1.v[0][1] + t1.v[1][1];
c = t2.v[0][0] + t2.v[1][0];
d = t2.v[0][1] + t2.v[1][1];
// flag means the the length of string is bigger than 1e9, can not;
if (flag || (d*x - b*y) % (a*d - b*c) || (c*x - a*y) % (b*c - a*d)) {
cout << "Impossible" << endl;
continue;
}
long long p = (d*x - b*y) / (a*d - b*c);
long long q = (c*x - a*y) / (b*c - a*d);
if (p < 0 || q < 0) {
cout << "Impossible" << endl;
continue;
}
matrix t3 = pow_mod(e, k - 1);
long long ans = p*(t3.v[0][0] + t3.v[1][0]) + q*(t3.v[0][1] + t3.v[1][1]);
cout << ans % MOD << endl;
}
// showtime;
return 0;
}