1D Spreadsheet
Time limit10sMemory limit512 MB
Given n cells that hold either a number or a link to another cell, process set, link, and range-sum queries on the resolved cell values.
- Level
Hard8 of 10
- Topics
- Tree, Array, Implementation
- Solved
- No attempts yet
Problem
You have a summer internship at a large software company. Your assigned project is a new application: a 1D spreadsheet.
A 1D spreadsheet is an array of cells numbered from 1 to . Cell either contains an integer or a link to another cell , in which case cell is linked to cell . Cyclic link dependencies are not allowed. At no moment is there a sequence of cells where is linked to , ..., and is linked to .
The value of a cell is defined as follows. If cell contains a number , then . Otherwise, . To evaluate a cell, follow the chain of links from it until you reach a cell that contains a number. Since there are no cycles, is uniquely defined for every cell at all times.
Bill, a colleague, added a range sum feature. Users can ask for and can change cell contents. Testing showed that Bill's implementation is slow. Your task is to write a program that processes a sequence of queries on the spreadsheet faster.
Input
The first line contains two integers and (), the number of cells and the number of queries.
The second line contains integers (), the initial cell values. Initially no cell contains a link.
Each of the next lines is one of the following queries.
set i x: cell is assigned the number ().link i j: cell is assigned a link to cell .sum l r: compute .
It is guaranteed that no cyclic dependencies occur at any point in time.
Output
For each sum l r query, print the answer on its own line, in the same order as the queries appear in the input.