This was a contest Q:
There are N numbers a[0],a[1]..a[N - 1]. Initally all are 0. You have to perform two types of operations :
- Increase the numbers between indices A and B by 1. This is represented by the command "0 A B"
- Answer how many numbers between indices A and B are divisible by 3. This is represented by the command "1 A B".
Input : The first line contains two integers, N and Q.
Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above.
Output : Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query.
Sample Input :
4 7 1 0 3 0 1 2 0 1 3 1
0 0 0 0 3 1 3 3 1 0 3
Sample Output :
4 1 0 2
Constraints :
1 <= N <= 100000 1 <= Q <= 100000 0 <= A <= B <= N - 1
I have no idea how to solve this. can you help please?
The time limit is 1 second. I tried brute force and i also tried saving number of divisors of 3 coming before ith element for each i.
here's my C code:
#include <stdio.h>
int nums[100*1000+20];
int d[100*1000+20];
int e[100*1000+20];
int dah[100*1000+20];
int main()
{
int n,q;
scanf("%d%d",&n,&q);
int h;
for(h=0;h<n;h++)
{d[h/100]++; e[h/1000]++; dah[h/10]++;}
int test;
for(test=0;test<q;test++)
{
int op,start,end;
scanf("%d%d%d",&op,&start,&end);
if(0==op)
{
int x;
for(x=start;x<=end;x++)
{
nums[x]++;
nums[x]%=3;
if(nums[x]==0)
{
d[x/100]++;
e[x/1000]++;
dah[x/10]++;
}
else if(nums[x]==1)
{
d[x/100]--;
e[x/1000]--;
dah[x/10]--;
}
}
}
else if(1==op)
{
int f;
int ans=0;
for(f=start;f<=end;)
{
if(f%1000==0&&f+1000<end)
{
ans+=e[f/1000];
f+=1000;
}
else if(f%100==0&&f+100<end)
{
ans+=d[f/100];
f+=100;
}
else if(f%10==0&&f+10<end)
{
ans+=dah[f/10];
f+=10;
}
else
{
ans+=(nums[f]==0);
f++;
}
}
printf("%d\n",ans);
}
}
return 0;
}
In this approach I save number of multiples of 3 between k*1000 and (k+1)*1000 and also the same thing for k*100 and (k+1)*100 and also for 10. this helps me query faster. but this yet gives me time limit exceed.