we assume that f(n) is the answer, so
f(n) = f(n-1) + f(n-2) + g(n-2)+h(n-2), here f(n-1) because of the vertical tile
f(n) = f(n-1) + f(n-2) + g(n-2)+h(n-2), here f(n-1) because of the vertical tile
f(n-2) because of the horizontal shaped tile and we must use 2 of them reducing to n-2
we assume g(n-2) is similar to f(n-2) accept there is a square in the top corner and this pattern is found when we use type 3 tiles and the symmetric case h(n-2) is same as g(n-2) except this time that square is in the bottom and this patter is found when we use type 4 tile. So we found the basic function but what is g(n) and h(n) in our known terms??
g(n) = f(n-1) + h(n-1); as we can use tile 4 and find structure f(n-1) or we use a horizontal type 2
tile in the bottom and find structure like h(n-1)
h(n) = f(n-1) + g(n-1) similar case.
for better visualization go here
so the basic matrix goes like
[ 1 1 1 1 ] [ f(n-1) ] [ f(n) ]
[ 1 0 0 0 ] * [ f(n-2) ] = [ f(n-1) ]
[ 0 1 0 1 ] [ g(n-2) ] [ g(n-1) ]
[ 0 1 1 0 ] [ h(n-2) ] [ h(n-1) ]
Here goes the code:
- #include <bits/stdc++.h>
- using namespace std;
- #define llu long long unsigned
- #define MOD 10007
- llu cm[4][4];
- void mul(llu a[4][4],llu b[4][4]){
- memset(cm, 0, sizeof(cm));
- for(int i = 0; i <4; i++){
- for(int j = 0; j <4; j++){
- for(int k = 0; k <4; k++){
- cm[i][j]+= ((a[i][k]%MOD)*(b[k][j]%MOD))%MOD;
- cm[j][j]%=MOD;
- }
- }
- }
- for(int i = 0; i <4; i++){
- for(int j = 0; j <4; j++){
- a[i][j] = cm[i][j]%MOD;
- }
- }
- }
- void ans(llu p[4][4], llu n){
- llu m[4][4] = {{1,1,1,1},{1,0,0,0},{0,1,0,1}, {0,1,1,0}};
- if(n == 1) return;
- ans(p, n/2);
- mul(p, p);
- if(n%2) mul(p, m);
- }
- int main(){
- int ts;
- scanf("%d", &ts);
- for(int p = 1; p <= ts; p++){
- llu n;
- scanf("%llu", &n);
- //printf("Case %d:\n", p);
- llu f[4][4] = {{1,1,1,1},{1,0,0,0},{0,1,0,1}, {0,1,1,0}};
- llu answer1;
- if(n == 1) answer1 = 1;
- else if(n == 2) answer1 = 2;
- else ans(f, n-2),answer1 = (f[0][0]*2)%MOD+f[0][1]%MOD+f[0][2]%MOD+f[0][3]%MOD;
- printf("Case %d: %llu\n",p, answer1%MOD);
- }
- return 0;
- }
Nice explanation! Thanks! ^_^
ReplyDeleteHappy to help :)
Delete