From f94e8e3dcd26311f5d8356df91fe510339623678 Mon Sep 17 00:00:00 2001 From: hanyixuanten Date: Wed, 28 Oct 2026 11:08:59 +0000 Subject: [PATCH] modified: P3374.cpp --- P3374.cpp | 48 +++++++++++++++++++----------------------- P3374.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 27 deletions(-) create mode 100644 P3374.md diff --git a/P3374.cpp b/P3374.cpp index c510fd2..152eaf2 100644 --- a/P3374.cpp +++ b/P3374.cpp @@ -1,34 +1,28 @@ #include using namespace std; -int n,m; -long long tree[500005]; -long long a[500005]; -int lowbit(int n){ - return n&(-n); +inline int lowbit(int x) {return x & (-x);}; +int n, m; +int a[500005]; +int num[500005]; +void add(int now, int nn) { + for(; now <= n; now += lowbit(now)) num[now] += nn; } -void modify(int x,long long k) -{ - for(;x<=n;x+=lowbit(x)) - tree[x]+=k; +int query(int now) { + int res = 0; + for(; now; now -= lowbit(now)) res += num[now]; + return res; } -long long query(int x){ - int ans; - for(;x;x-=lowbit(x)) - ans=ans+tree[x]; - return ans; -} -int main(){ - scanf("%d%d",&n,&m); - for(int i=1;i<=n;++i){ - scanf("%lld",&a[i]); - modify(i,a[i]); - } - while(m--){ - int op,x; - long long y; - scanf("%d%d%lld",&op,&x,&y); - if(op==1) modify(x,y); - else printf("%lld\n",query(y)-query(x-1)); +int main() { + scanf("%d%d", &n, &m); + for(int i = 1; i <= n; ++i) scanf("%d", &a[i]), add(i, a[i]); + while(m--) { + int op, x, y; + scanf("%d%d%d", &op, &x, &y); + if(op == 1) { + add(x, y); + } else{ + printf("%d\n", query(y) - query(x - 1)); + } } return 0; } \ No newline at end of file diff --git a/P3374.md b/P3374.md new file mode 100644 index 0000000..f51dbfe --- /dev/null +++ b/P3374.md @@ -0,0 +1,63 @@ +# P3374 【模板】树状数组 1 + +## 题目描述 + +如题,已知一个数列,你需要进行下面两种操作: + +- 将某一个数加上 $x$; + +- 求出某区间每一个数的和。 + +## 输入格式 + +第一行包含两个正整数 $n,m$,分别表示该数列数字的个数和操作的总个数。 + +第二行包含 $n$ 个用空格分隔的整数,其中第 $i$ 个数字表示数列第 $i$ 项的初始值。 + +接下来 $m$ 行每行包含 $3$ 个整数,表示一个操作,具体如下: + +- `1 x k` 含义:将第 $x$ 个数加上 $k$; + +- `2 x y` 含义:输出区间 $[x,y]$ 内每个数的和。 + +## 输出格式 + +输出包含若干行整数,即为所有操作 $2$ 的结果。 + +## 输入输出样例 #1 + +### 输入 #1 + +``` +5 5 +1 5 4 2 3 +1 1 3 +2 2 5 +1 3 -1 +1 4 2 +2 1 4 +``` + +### 输出 #1 + +``` +14 +16 +``` + +## 说明/提示 + +【数据范围】 + +对于 $30\%$ 的数据,$1 \le n \le 8$,$1\le m \le 10$; +对于 $70\%$ 的数据,$1\le n,m \le 10^4$; +对于 $100\%$ 的数据,$1\le n,m \le 5\times 10^5$,$1\le x\le y\le n$,$-2^{31}\le k<2^{31}$。 + +数据保证对于任意时刻,$a$ 的任意子区间(包括长度为 $1$ 和 $n$ 的子区间)和均在 $[-2^{31}, 2^{31})$ 范围内。 + + +样例说明: + + ![](https://cdn.luogu.com.cn/upload/pic/2256.png) + +故输出结果 $14$ 和 $16$。 \ No newline at end of file