Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Sunday, May 25, 2014

POTIONS-Potions Class


Potions Class

Below given python code for potions spoj or potions class spoj.
In question a function is given for range query and seeing the number of query(q<100000) every query should be done in constant time O(1).Now having a look on function and trying to simplify it.

Now “w” is constant so taking it outside of summation

Now subtracting and adding “x” to  “i”  sp,
Now rearranging the above we get  
Since “x” is constant so taking it out of summation and taking common with












Now owr answer will be :..





If you have any problem in understanding the above logic you can mail me @ raj.nishant360@gmail.com

Below is Python 2.7 implementation of above logic.

import sys
t=int(sys.stdin.readline())
while t:
    n,q=map(int,sys.stdin.readline().split())
    s=raw_input().split()
    cum=[]
    cum2=[]
    for i in range(0,n+1):
        cum.append(0)
        cum2.append(0)
    for i in range(1,n+1):
        cum[i]=cum[i-1] + int(s[i-1])
        cum2[i]=cum2[i-1]+i*(int(s[i-1]))
    for i in range(0,q):
        w,x,y,z=map(int,sys.stdin.readline().split())
        lower = y+x
        higher = z+x
        result=(cum2[higher]-cum2[lower-1] + (w-x)*(cum[higher]-cum[lower-1]))%1000000007
        sys.stdout.write(str(result))
        sys.stdout.write("\n")
    t=t-1

No comments:

Post a Comment

Your comment is valuable to us