题目1 : Matrix Sum
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
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 y1: Return the sum of every element Axy for x1 ≤ x ≤ x2, y1 ≤ y ≤ y2.
输入
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
输出
For each Sum operation output a non-negative number denoting the sum modulo 109+7.
- 样例输入
-
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
- 样例输出
-
1 2 3
肯定是二维线段树,虽然思路明白,但是不会写,先用树状数组吧。
#include<stdio.h> #include<string.h> #include<stdlib.h> int N, M, x1, x2, y1, y2, v; long long BIT2[1005][1005]; char str[10]; int lowbit(int x) { return x & (-x); } void add(int x, int y, int val) { for (int i = x; i <= N; i += lowbit(i)) { for (int j = y; j <= N; j += lowbit(j)) { BIT2[i][j] += val; BIT2[i][j] %= 1000000007; } } } long long sum(int x, int y) { long long ret = 0; for (int i = x; i > 0; i -= lowbit(i)) { for (int j = y; j > 0; j -= lowbit(j)) { ret += BIT2[i][j]; ret %= 1000000007; } } return ret; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #endif scanf("%d%d", &N, &M); memset(BIT2, 0, sizeof(BIT2)); for (int i = 0; i < M; i++) { scanf("%s", str); if (strcmp(str, "Add") == 0) { scanf("%d%d%d", &x1, &y1, &v); x1++, y1++; add(x1, y1, v); } else { scanf("%d%d%d%d", &x1, &y1, &x2, &y2); x2++, y2++; long long ans = sum(x2, y2); ans = ans - sum(x1, y2) - sum(x2, y1) + sum(x1, y1); while (ans < 0) { ans += 1000000007; } printf("%lld ", ans); } } return 0; }