Time Limit: 0.5 second(s) | Memory Limit: 32 MB |
Given a code (not optimized), and necessary inputs, you haveto find the output of the code for the inputs. The code is as follows:
int a, b, c, d, e, f;
int fn( int n ) {
if( n == 0 ) return a;
if( n == 1 ) return b;
if( n == 2 ) return c;
if( n == 3 ) return d;
if( n == 4 ) return e;
if( n == 5 ) return f;
return( fn(n-1) + fn(n-2) + fn(n-3) + fn(n-4) + fn(n-5) + fn(n-6) );
}
int main() {
int n, caseno = 0, cases;
scanf("%d", &cases);
while( cases-- ) {
scanf("%d %d %d %d%d %d %d", &a, &b, &c, &d, &e, &f, &n);
printf("Case %d: %d\n", ++caseno, fn(n) % 10000007);
}
return 0;
}
Input
Input starts with an integer T (≤ 100),denoting the number of test cases.
Each case contains seven integers, a, b, c, d, e, f and n.All integers will be non-negative and 0 ≤ n ≤ 10000 and the eachof the others will be fit into a 32-bit integer.
Output
For each case, print the output of the given code. The given code may have integer overflow problem in the compiler, so be careful.
Sample Input | Output for Sample Input |
5 0 1 2 3 4 5 20 3 2 1 5 0 1 9 4 12 9 4 5 6 15 9 8 7 6 5 4 3 3 4 3 2 54 5 4 | Case 1: 216339 Case 2: 79 Case 3: 16636 Case 4: 6 Case 5: 54 |
题意: 让你求上面代码的运行结果.
分析: 上面的代码是递归形式, 化成递推就是 f(n) = f(n-1)+f(n-2)+f(n-3)+f(n-4)+f(n-5)+f(n-6); 那么就可以进行递推了, 但是递推还是有点慢, 因为T比较大, 递推都是可以用矩阵运算来加速的, 构造一个6乘6的矩阵, 然后快速幂运算, 把复杂度降到6*6*6*log*(n); 注意我的写法是不能处理0的情况的, 这次吃了大亏了.
#include<bitset>
#include<map>
#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<stack>
#include<queue>
#include<set>
#define inf 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))
#define F first
#define S second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
inline int in()
{
int res=0;char c;int f=1;
while((c=getchar())<'0' || c>'9')if(c=='-')f=-1;
while(c>='0' && c<='9')res=res*10+c-'0',c=getchar();
return res*f;
}
const int N=100010,MOD=10000007;
int q[7],n;
struct M
{
int a[6][6];
void init()
{
mem(a,0);
int j=1;
for(int i=0;i<5;i++)
{
a[i][j++]=1;
}
for(int i=0;i<6;i++) a[5][i]=1;
}
};
M mul(M x,M y)
{
M ret;
mem(ret.a,0);
for(int i=0;i<6;i++)
{
for(int k=0;k<6;k++)
{
if(x.a[i][k]==0) continue;
for(int j=0;j<6;j++)
{
ret.a[i][j] = (ll(1LL*x.a[i][k]*y.a[k][j] + ret.a[i][j]))%MOD;
}
}
}
return ret;
}
M solve()
{
M ans,x;
ans.init();
x.init();
n--;
while(n>0)
{
if(n & 1) ans = mul(ans,x);
x=mul(x,x);
n>>=1;
}
return ans;
}
int main()
{
int T=in(),ca=1;
while(T--)
{
for(int i=0;i<6;i++) q[i]=in()%MOD;
n=in();
if(n==0) ////特判!!
{
printf("Case %d: %d\n", ca++, q[0]);
continue;
}
M ans=solve();
int ret=0;
for(int i=0;i<6;i++) ret = ((ll)(ret+1LL*ans.a[0][i]*q[i]))%MOD;
printf("Case %d: %d\n", ca++, ret);
}
return 0;
}