What I did was this. For reverse I kept count of no.of reverse operations. If this count is odd, your ans will be the last element of array & if even it will be the first element. I stored this element in ans_to_print variable. Since we didn’t need to manipulate it further. I deleted the element from the array. So, my trick of last for odd & first for even worked better. Now, for add & multiply, I kept two variable add & mult. As we know if we add some number to another number & than multiply with some another number like (10+50)*20, it will be 10*20 + 50*20. So picking a trick from this I modified add & mult as below:
if(ch=='A')
add=(add+a)%c;
else if(ch=='M')
mult=(mult*b)%c;
add=(add*b)%c; /// This helped in maintaining the order of addition & multiplication.
A better/time effective approach to (a*b)%c could be
long long int mult(long long int a, long long int b, long long int c)
{
a = a % c;
b = b % c;
long long int z = 0;
for (1; a; a >>= 1){
if(a & 1)
if((z =z+ b) >= c)
z = z- c;
if((b = 2 * b) >= c)
b =b- c;
}
return z;
}
Why my this solution: http://www.codechef.com/viewsolution/3206481
was giving nzec . All numbers in the listwere integers so i was just making a array out of those numbers while just making a simple list was working fine.
Can u please explain what this function does in detail…
long long multiple(long long a, long long b, long long c) // a * b % c
{
if (b == 0) {
return 0
}
long long ret = multiple(a, b >> 1, c)
ret = (ret + ret) % c
if (b & 1) {
ret = (ret + a) % c
}
return ret
}
It looks like “void add(int s)” has a bug. You should have one more mod after the +. Try to find such tiny bugs around, and thus your debug skills will be improved fast.
The multiplication operator in your code, although mod c, may exceed unsigned long long. Please read the editorial to find the tricky way to get the product withou any exceeding. Thanks.
@aq1_ If you’ll see addmod function, you have done x-m+y, but if even this “x-m+y” is greater than c, we again need to take the mod. You function should have the recursive call which returns(x+y+m) when x+y-m<0.
“multiplicativeConstant = (multiplicativeConstant * bModC) % C;” may exceed the unsigned long long when multiplication, please look into the editorial to find the solution to avoid exceeding.