QUESTION LINK - https://www.codechef.com/problems/KOL15C
my code is generating TLE, can't understand what to do
#include<stdio.h> int main() { int N,U,a,b,i; scanf("%d%d",&N,&U); int A[N]; for(i=0;i<N;++i) { A[i]=0; } while(U--) { scanf("%d%d",&a,&b); for(i=0;a*i+b-1<N;++i) { A[a*i+b-1]++; } } for(i=0;i<N;++i) { printf("%d ",A[i]); } return(0); }
Asked by: Shubrojyoti_Karmakar on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.
Yes, Normal Brute force will result in TLE. Because since your N is of order 10^5 and number of updates is 2*10^5 thus in worst case scenario your code will be performing 2*10^10 iterations. Time Complexity of your code is O(U*N). Thus will result in Time Limit Exceeded Error.
To solve this we have a standard algorithm called Mo's Algorithm which is a special case of Square Root Decomposition. The time complexity of this algorithm is O((U+N)*sqrt(N)). Which will easily pass in 1 sec.
Happy Coding :)
I don't this MO's is necessary over here.
Just find the range of L and R (depending upon x) where update is required for each query and then add +1 to arr[L]
and add -1 to arr[R+1].
Do this for all the queries.
At the end do a prefix sum to get the final array.
A similar question was done in Wednesday's class.