Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fn foods.But there are only p foods,so you should tell him fn mod p.
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109,p is a prime number,and p≤109+7.
#include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> using namespace std; #define ll __int64 #define mod 1000000007 #define inf 999999999 //#pragma comment(linker, "/STACK:102400000,102400000") ll a,b,c,n,p; struct is { ll a[10][10]; }; is juzhenmul(is a,is b,ll hang ,ll lie) { int i,t,j; is ans; memset(ans.a,0,sizeof(ans.a)); for(i=1;i<=hang;i++) for(t=1;t<=lie;t++) for(j=1;j<=lie;j++) { ans.a[i][t]+=(a.a[i][j]*b.a[j][t]); ans.a[i][t]%=(p-1); } return ans; } is quickpow(is ans,is a,ll x) { while(x) { if(x&1) ans=juzhenmul(ans,a,3,3); a=juzhenmul(a,a,3,3); x>>=1; } return ans; } ll quickpow1(ll a,ll n) { ll mul=1; if(a%p==0) return 0; while(n) { if(n&1) mul*=a,mul%=p; n>>=1; a=a*a; a%=p; } return mul; } int main() { is ans,base,gg; int gggg; scanf("%d",&gggg); while(gggg--) { ll fn; scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p); if(n>2) { memset(ans.a,0,sizeof(ans.a)); ans.a[1][1]=1; ans.a[2][2]=1; ans.a[3][3]=1; memset(base.a,0,sizeof(base.a)); base.a[1][1]=c; base.a[1][2]=1; base.a[2][1]=1; base.a[3][1]=1; base.a[3][3]=1; ans=quickpow(ans,base,n-2); gg.a[1][1]=b; gg.a[1][2]=0; gg.a[1][3]=b; ans=juzhenmul(gg,ans,1,3); fn=ans.a[1][1]; } else { if(n==1) fn=0; else fn=b; } printf("%I64d\n",quickpow1(a,fn)); } return 0; }