Monday, 18 June 2012

UVa 12470 - Tribonacci Solution

#include<iostream>
#include<list>
#include<string>
#include<cstring>
#include<sstream>
#include<cctype>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stack>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<map>
#include<set>
#include<utility>
#include<iomanip>
#include<queue>


using namespace std;
#define MOD 1000000009

struct A{
    long long arr[10][10];
};

A MatrixMulti(A a, A b)
{
    A result;
    int i,j,k;
    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
        {
            result.arr[i][j]=0;
            for(k=0;k<3;k++)
                result.arr[i][j]+=(a.arr[i][k]*b.arr[k][j]);
            result.arr[i][j]=result.arr[i][j]%MOD;
        }
    return result;
}

A BigMod(A a, long long n)
{
    A ret;
    int i,j;
    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
            {
                if(i==j)
                ret.arr[i][j]=1;
                else
                ret.arr[i][j]=0;
            }

    while(n)
    {
        if(n & 1)
    ret=MatrixMulti(ret,a);
        a=MatrixMulti(a,a);
        n>>=1;
    }
    return ret;
}

int main()
{
    A initialMatrix,ans;
    long long n,m,i,j;

    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
            initialMatrix.arr[i][j]=1;

    initialMatrix.arr[1][1]=initialMatrix.arr[1][2]=initialMatrix.arr[2][0]=initialMatrix.arr[2][2]=0;
    while(cin>>n && n)
    {
       
            if(n==1)
            {
                cout<<"0"<<endl;
                continue;
            }
            if(n==2)
            {
                cout<<"1"<<endl;
                continue;
            }


            ans=BigMod(initialMatrix,n-3);
            cout<<(ans.arr[0][0]*2+ans.arr[0][1])%MOD<<endl;
    }
return 0;
}

1 comment: