art-hack's blog

By art-hack, history, 5 years ago, In English

Hey Everyone, So I saw this problem in one of the contests on Codechef(link)

Problem Statement

You are given two integers N and M. Find the number of sequences A1, A2,…,AN, where each element is an integer between 1 and M (inclusive) and no three consecutive elements are equal. Since this number could be very large, compute it modulo 109+7.

So I used my general code for Matrix Exponentiation but got a TLE.

My submission

People have used matrix exponentiation for the same and got a full score.

Selected submission

Things that I have tried already are

  • Switching ll with int
  • Reserving the size of the vector already.

Please tell me what I can optimize more in my code so that we do not face this problem in any of the Matrix Exponentiation problems?

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
5 years ago, # |
Rev. 3   Vote: I like it +20 Vote: I do not like it

Modulo is a costly operation and in your multiply function and at some other places you have used unncessary modulo (a % mod + ((b % mod)*(c % mod)) % mod which can be replaced with (a + (b * c) % mod) % mod (since a,b,c are long long. In case they are not long long typecast them).

»
5 years ago, # |
  Vote: I like it +12 Vote: I do not like it

You are passing Vectors by value. Pass them by reference and it should solve the problem.

  • »
    »
    5 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Does creating a vector and then passing it using its reference have such a significant impact over just passing it?.

    • »
      »
      »
      5 years ago, # ^ |
      Rev. 2   Vote: I like it +3 Vote: I do not like it

      yes, everytime you call a function, you make unnecessary copies of it.

    • »
      »
      »
      5 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Passing without reference creates a new copy of vector every time while this is not the case with reference . So yes it has a significant effect.