Problem Link:
https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/angry-neighbours/
#include<bits/stdc++.h>
using namespace std;
void multiply(long long int a[2][2],long long int b[2][2])
{
long long int mul[2][2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (int k = 0; k < 2; k++)
{
mul[i][j] += (a[i][k]*b[k][j])%1000000007;
mul[i][j]=mul[i][j]%1000000007;
}
}
}
for (int i=0; i<2; i++)
for (int j=0; j<2; j++)
a[i][j] = mul[i][j];
}
void pass(long long int arr2[2][2],long long int n)
{
long long int result[2][2]={1,0,0,1};
while(n!=0)
{
if(n%2==1)
multiply(result,arr2);
multiply(arr2,arr2);
n/=2;
}
cout<<(result[0][0]*3+result[0][1]*2)%1000000007<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
long long int arr2[2][2]={1,1,1,0};
long long n;
cin>>n;
if(n==1)
{
cout<<"2"<<endl;
continue;
}
if(n==2)
{
cout<<"3"<<endl;
continue;
}
pass(arr2,n-2);
}
return 0;
}
https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/angry-neighbours/
#include<bits/stdc++.h>
using namespace std;
void multiply(long long int a[2][2],long long int b[2][2])
{
long long int mul[2][2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (int k = 0; k < 2; k++)
{
mul[i][j] += (a[i][k]*b[k][j])%1000000007;
mul[i][j]=mul[i][j]%1000000007;
}
}
}
for (int i=0; i<2; i++)
for (int j=0; j<2; j++)
a[i][j] = mul[i][j];
}
void pass(long long int arr2[2][2],long long int n)
{
long long int result[2][2]={1,0,0,1};
while(n!=0)
{
if(n%2==1)
multiply(result,arr2);
multiply(arr2,arr2);
n/=2;
}
cout<<(result[0][0]*3+result[0][1]*2)%1000000007<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
long long int arr2[2][2]={1,1,1,0};
long long n;
cin>>n;
if(n==1)
{
cout<<"2"<<endl;
continue;
}
if(n==2)
{
cout<<"3"<<endl;
continue;
}
pass(arr2,n-2);
}
return 0;
}
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন