Блог пользователя ritik652000

Автор ritik652000, история, 3 года назад, По-английски

Can someone please help me, I got TLE on O(N) on 714B?

mod = 10**9 + 7
for _ in range(int(input())):
    n = int(input())
    arr = list(map(int,input().split()))
    count = arr[0]
    f = 1
    for i in range(1,n):
        count&=arr[i]
        f*=i
    f//=(n-1)
    t = arr.count(count)
    p = 1
    if(t<=1):
        print(0)
    else:
        
        p = t*(t-1)
        re = p*f
        print(re%mod)
  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

I think its the 'f', you calculate f = n!, but for n = 2e5 the value is too big and the time to calculate this in python is too large. As you want the answer modulo M, you can try to calculate the answer modulo M in the for, and use modular inverse for the division.

»
3 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Calculating f for a large n will be too slow. Instead you can take mod at each step. Replacing f*=i by if i<n-1: f=(f*i)%mod and removing the f//=n-1 might work.

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

For large numbers (in this case of size 1e5) even simple operations like multiplication will behave like a linear time operation. In this case, while calculating factorial of do modulo operation after each multiplication to keep the size of the number small. -> f = (f*i)%mod