Giving TLE , why, please explain?

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define nL “\n”
#define pb push_back

ll p;
ll k;
vector b, c;

vector<vector> multiply(vector<vector> A, vector<vector> B)
{
vector<vector> C(k + 2, vector(k + 2)); // matrix multiplication (A * B) => store in C

for (int i = 1; i <= k+1; i++)
{
	for (int j = 1; j <= k+1; j++)
	{
		for (int x = 1; x <= k+1; x++)
		{
			C[i][j] = (C[i][j] + (A[i][x] * B[x][j]) % p) % p;
		}
	}
}
return C;

}

vector<vector> power(vector<vector> A, int p)
{
if (p == 1)
return A;

if (p & 1) //odd
{
	return multiply(A, power(A, p - 1));
}

vector<vector<ll>> X = power(A, p / 2);     //even
return multiply(X, X);

}

ll compute(ll n)
{
if (n == 0)
return 0;

if (n <= k)
	return b[n - 1];

// step 1  find F1(stores first k terms)
vector<ll> F1(k + 2);
F1[1] = 0;
for (int i = 2; i <= k+1; i++)
{
	F1[i] = b[i - 2];
}

//step2 - compute T(transformation matrix)
vector<vector<ll>> T(k + 2, vector<ll>(k + 2));

for (int i = 1; i <= k+1; i++)
{
	for (int j = 1; j <= k+1; j++)
	{
		if(i == 1 && j == 1)
        {
            T[i][j] = 1;
            continue;
        }

        if(i == k+1 && j > 1)
        {
            T[i][j] = c[k - j + 1];
            continue;
        }

        if(j == i+1)
        {
            T[i][j] = 1;
        }
        else
           T[i][j] = 0;
	}
}


//step3 - cal T ^ n
T = power(T, n);

//step 4 - cal res by T^n-1 * F1
ll res = 0;
for (int i = 1; i <= k+1; i++)
{
	res = (res + (T[1][i] * F1[i]) % p) % p;
}
return res;

}

int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);

ll t, n, num;

cin >> t;
while (t--)
{
	cin >> k;

	for (int i = 1; i <= k; i++)
	{
		cin >> num;
		b.pb(num);
	}

	for (int i = 1; i <= k; i++)
	{
		cin >> num;
		c.pb(num);
	}
    
    ll m, n;
	cin >> m >> n >> p;

	ll Sn = compute(n);
    ll Sm1 = compute(m-1);

    ll reqSum = (Sn - Sm1 + p) % p;
    cout << reqSum << nL;

	b.clear();
	c.clear();
}

return 0;

}

@devang_11912089,

  1. In the power function, the datatype of p is int instead of ll, which will cause overflow issues.
    vector<vector<ll>> power(vector<vector<ll>> A, ll p)

  2. If n<=k, you are just returning b[n-1].

if (n <= k){
ll sum = 0;
for(int i=0;i<n;i++){
sum += b[i];
}
return sum;
}

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.