Given N(<=10^5 ) digits (0<=each digit<=9), and M(<=10^5) queries, each consisting of one x(1<=x<=n). Print B1 - B2.
B1 = sum of all ( ax - ay ) such that x > y and ax > ay.
B2 = sum of all ( ax - ay ) such that x > y and ax < ay.
EXPLANATION:
We define a new array A where A[i][j] is the number of times digit i occurs in a1,a2,…aj.
Code:
for i=0 to 9: // calculate the row A[i] for each i=0 to 9.
for j=1 to n:
A[i][j]=A[i][j-1];
if a[j]==i: A[i][j]++; // if a[j]==i, current value one more than previous.
For each input query p, let q=ap, we do:
B1=0
for i=0 to q-1: // sum of those where ax > ay
B1 += A[i][p-1]*(q-i) // difference is (x-i)
B2=0
for i=q+1 to 9: // sum of those where ax < ay
B2 += A[i][p-1]*(q-i) // difference is (x-i)
print B1-B2
Time Complexity: O( N * 10 ) [ Computation of A ] + M * 10 ( For M queries.)
Can someone please explain what is happening in the 1st code? In the A[i][j] array? Is A[i][j] a character array or integer array? I am unable to understand the logic of this solution.
It says, when a new digit is added, number of times every digit has occurred so far remains same except for the newly added digit. For newly added digit, it is 1 + count before this digit was added.
If you re-read the problem, I hope you would understand now.
My submitted solution also precalculates all the steps with O(10 * N) time complexity and O(N) space.
Queries become constant.
Lets say “A” of size N to store the precalculated values and “a” the input:
for step = 0 to n
int ans
for i = step-1 to 0
t = a[step] - a[i]
if t == 0 // Meaning that we have calculated the values for
// the same number previously and we only need to retrieve that value from A
ans += A[i];
A[step] = ans;
break;
end if
ans += abs(t);
A[step] = ans;
end for
end for
Please help…I was getting WA for my submissions. I think, I used the above mentioned algo in my code. Can anyone please point out the error in my code! My Code
https://www.codechef.com/viewsolution/9957518
You need to first precompute the value and then find the answer in constant amount of time, if you do not do so,
you will end up with an algorithm with complexity of O(m*n) in worst case scenario because for every query you will process the array.