Matrix Sum
Problem Description
You are given an N × N matrix. At the beginning every element is 0. Write a program supporting 2 operations:
1. Add x y value: Add value to the element Axy. (Subscripts starts from 0
2. Sum x1 y1 x2 y2: Return the sum of every element Axy for x1 ≤ x ≤ x2, y1 ≤ y ≤ y2.
Input
The first line contains 2 integers N and M, the size of the matrix and the number of operations.
Each of the following M line contains an operation.
1 ≤ N ≤ 1000, 1 ≤ M ≤ 100000
For each Add operation: 0 ≤ x < N, 0 ≤ y < N, -1000000 ≤ value ≤ 1000000
For each Sum operation: 0 ≤ x1 ≤ x2 < N, 0 ≤ y1 ≤ y2 < N
Output
For each Sum operation output a non-negative number denoting the sum modulo 109+7 .
Sample Input
5 8
Add 0 0 1
Sum 0 0 1 1
Add 1 1 1
Sum 0 0 1 1
Add 2 2 1
Add 3 3 1
Add 4 4 -1
Sum 0 0 4 4
Sample Output
1
2
3
题意:
给你一个N*N二维矩阵,初始值时都为0,有两种操作
1:单点修改值
2:给出一个子矩阵的左上和右下角的坐标,询问一个子矩形范围内的值的和.
解题思路:
还是看官方的题解吧。。。《Matrix Sum》题目分析
Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
const int maxn=1000+5,
mod=1e9+7;
LL BIT[maxn][maxn];
int N,m;
int lowbit(int x)
{
return x&(-x);
}
void add(int x,int y,int val)
{
for(int i=x;i<maxn;i+=lowbit(i))
{
for(int j=y;j<maxn;j+=lowbit(j))
{
BIT[i][j]=(BIT[i][j]+val)%mod;
}
}
}
int sum(int x,int y)
{
LL ret=0;
for(int i=x;i>0;i-=lowbit(i))
{
for(int j=y;j>0;j-=lowbit(j))
{
ret=(ret+BIT[i][j])%mod;
}
}
return (int)ret;
}
int main()
{
mem(BIT,0);
scanf("%d%d",&N,&m);
char op[10];
for(int i=0;i<m;i++)
{
scanf("%s",op);
if(op[0]=='A')
{
int x,y,val;
scanf("%d%d%d",&x,&y,&val);
x++,y++;
add(x,y,val);
}
else
{
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
x1++,x2++,y1++,y2++;
int res=(sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1)+mod)%mod;
printf("%d\n",res);
}
}
return 0;
}