Looking For Future Payment? Must Read!

Bitcoin Red Diamond is a peer-to-peer crypto currency and can be termed as a modified version of the technology on which bitcoin was built. BRD is anonymous, fast and convenient tokens The main…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Lazy propagation in Segment Tree

In the last last tutorial we learned how to build a Segment tree, query it and update point values to it. In this tutorial we will learn a useful technique Lazy Propagation for Segment trees. Using lazy propagation we can update a range in the tree efficiently. In this technique we update the value in a lazy manner, as the name suggests itself. Being lazy, values are not updated unless needed. Hence “lazy propagation” roughly translates to propagating values from root in a lazy manner.

Let’s make it clear with an example. Suppose we’ve built a Segment tree and there are two types of queries available on the tree. First one is update, which adds some value to nodes in a particular range. Second type is query for sum, which asks for sum of node values for a given range. In lazy propagation, “Lazy” refers to the idea that we will not update the range down to the leaf nodes every time it is called. Because the query for sum is called in the last, we will accumulate the values in an another array every time update() is called and these accumulated values will provide sum only for query which asks for sum in a range. Let’s take an example to make the concept clear.

Question
You are given an array of N elements, which are initially all 0. After that you will be given C commands. They are:
* 0 p q v — you have to add v to all numbers in the range of p to q (inclusive), where p and q are two indexes of the array.

* 1 p q — output a line containing a single integer which is the sum of all the array elements between p and q (inclusive)

Input:
In the first line you’ll be given T, number of test cases.

Each test case will start with N (N<=100 000) and C (C<=100 000). After that you’ll be given C commands in the format as mentioned above. 1 <= p,q <= N and 1 <= v <= 10⁷.

Output:
Print the answers of the queries.

Add a comment

Related posts:

Master AP Chemistry with the expert help from online AP chemistry tutor

From atomic theory to thermodynamics, AP chemistry has a way of getting into a student’s head. But we can surely beat the AP chemistry blues by finding some ways to learn it better. Students need not…

What is collabee?

collabee is a team collaboration tool that helps teams collaborate by sharing tasks, files, decisions, and events in a single issue page. collabee can be used for various use cases, including product…

Dear Summer Body

A girls letter to her Summer Body. I hope it helps you to read it as it helped me to write it.