Digital internship Mobile phones tree array

Keywords: Mobile

describe
Suppose that the fourth generation mobile phone base station in an area can receive mobile phone signals. The area is square, forming an S * S-size matrix with row and column numbers from 0 to S-1. Each block contains a base station. The number of active phones in the phone may change because the phone can be moved freely between blocks or turned on and off.

Write a program to receive these reports and answer the total number of currently active phones in any rectangular area.

Input:
The input consists of two parts: instruction and the meaning it represents
When instruction=0, initialize the area matrix to make it all 0, and input n to represent the matrix size
When instruction=1, enter x,y,A to indicate (x,y) to add A mobile phone
When instruction=2, input x1,y1,x2,y2, and output the number of mobile phones in the whole area between (x1,y1) and (x2,y2)

sample input
0 4
1 1 2 3
2 0 0 2 2
1 1 1 2
1 1 2 -1
2 1 1 2 3
3
sample output
3
4

#include <iostream>
using namespace std;

int c[1025][1025];
int n;
int lowbit(int x)
{
	return x & -x;
}

void update(int x, int y, int delta)               //Update tree array
{
	for (int i = x; i <= n; )
	{
		for (int j = y; j <= n;)
		{
			c[i][j] += delta;
			j = j + lowbit(j);
		}
		i = i + lowbit(i);
	}
}

int calculate(int x, int y)                         //Summation
{
	int sum = 0;
	for (int i = x; i > 0;)
	{
		for (int j = y; j > 0;)
		{
			sum += c[i][j];
			j = j - lowbit(j);
		}
		i = i - lowbit(i);
	}
	return sum;
}

int main()
{
	int ins;
	while (1)
	{
		cin >> ins;
		if (ins == 3)
			break;
		if (ins == 0)
		{
			cin >> n;
			for (int i = 0; i <= n; i++)
				for (int j = 0; j <= n; j++)
					c[i][j] = 0;
			continue;
		}
		if (ins == 1)
		{
			int x, y, A;
			cin >> x >> y >> A;
			update(x + 1, y + 1, A);
		}
		else if (ins == 2)
		{
			int x1, y1, x2, y2;
			cin >> x1 >> y1 >> x2 >> y2;
			int result;
			result = calculate(x2 + 1, y2 + 1) + calculate(x1, y1) - calculate(x1, y2 + 1) - calculate(x2 + 1, y1);
			cout << result << endl;
		}
	}
	return 0;
}

Posted by H-Fish on Wed, 18 Dec 2019 08:53:16 -0800