Time Limit: 2 second(s) | Memory Limit: 32 MB |
Zibon just started his courses in Computer science. After having some lectures on programming courses he fell in love with strings. He started to play with strings and experiments on them. One day he started a string of arbitrary (of course positive) length consisting of only {a, b}. He considered it as 1st string and generated subsequent strings from it by replacing all the b's with ab and all the a's with b. For example, if he ith string is abab, (i+1)th string will be b(ab)b(ab) = babbab. He found that the Nth string has length X and Mth string has length Y. He wondered what will be length of the Kth string. Can you help him?
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case begins with five integers N, X, M, Y, K. (0 < N, M, X, Y, K < 109 and N ≠ M).
Output
For each case print one line containing the case number and L which is the desired length (mod 1000000007) or the string "Impossible" if it's not possible.
Sample Input | Output for Sample Input |
2 3 16 5 42 6 5 1 6 10 9 | Case 1: 68 Case 2: Impossible |
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<map>
#include<cmath>
#include<vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
#define pi acos(-1.0)
#define eps 1e-10
#define pf printf
#define sf scanf
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
#define e tree[rt]
#define _s second
#define _f first
#define all(x) (x).begin,(x).end
#define mem(i,a) memset(i,a,sizeof i)
#define for0(i,a) for(int (i)=0;(i)<(a);(i)++)
#define for1(i,a) for(int (i)=1;(i)<=(a);(i)++)
#define mi ((l+r)>>1)
#define sqr(x) ((x)*(x))
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
ll p[3][3],ans[3][3];
int m,n,x,y,k,t,XX,Xx,xX,YY,Yy,yY;//定义成x1,y1什么的CE了,很迷
void multi(ll a[][3],ll b[][3])
{
ll tmp[3][3];
mem(tmp,0);
for1(i,2)
for1(j,2)
for1(k,2)
tmp[i][j]=(tmp[i][j]+a[i][k]*b[k][j])%mod;
for1(i,2)
for1(j,2)
a[i][j]=tmp[i][j];
}
void init()
{
mem(ans,0);
mem(p,0);
ans[1][1]=ans[2][2]=1;
p[1][1]=p[1][2]=p[2][1]=1,p[2][2]=0;
}
void solve(int n,int& x,int& y)//矩阵快速幂计算x y的系数
{
n--;
init();
while(n)
{
if(n&1)multi(ans,p);
n>>=1;
multi(p,p);
}
x=(ans[2][1]+ans[2][2])%mod;
y=(ans[1][1]+ans[1][2])%mod;
}
int main()
{
sf("%d",&t);
for1(i,t)
{
init();
int tag=0;
sf("%d%d%d%d%d",&x,&n,&y,&m,&k);
pf("Case %d: ",i);
solve(x,XX,YY);
solve(y,Xx,Yy);
solve(k,xX,yY);
if((XX*m-Xx*n)%(Yy*XX-YY*Xx))//不能整除,说明不能求出满足的x y,因为 m n没有mod过1e9+7,在x y大于0时要求出解,否则不满足
puts("Impossible");
else
{
ll YYY=(XX*m-Xx*n)/(Yy*XX-YY*Xx);
if((n-YY*YYY)%XX)
puts("Impossible");
else
{
int XXX=(n-YY*YYY)/XX;
if(XXX<0||YYY<0)
{
puts("Impossible");
}
else
{
ll ans=((ll)XXX*xX%mod+(ll)YYY*yY%mod)%mod;
ans=(ans+mod)%mod;
pf("%lld\n",ans);
}
}
}
}
return 0;
}