P1001 A+B Problem-题解

· · 题解

本篇题解仅供娱乐

题意

输入两个数,输出他们的和。

思路

这是一道 树状数组 的练手好题。

输入两个数,就是单点修改;
加起来,就是求区间和。

代码

#include<bits/stdc++.h>
using namespace std;

int n = 2; 
int tree[10];

int lowbit(int x) //树状数组少不了的,不多说了
{
    return x & -x;
}

void add(int x, int k) //单点修改
{
    while (x <= n) //如果不出界就继续
    {
        tree[x] += k; //一路往上更新节点
        x += lowbit(x);
    }
    return;
}

int sum(int x) //求区间和
{
    int s = 0;
    while (x != 0) //不出界就继续
    {
        s += tree[x]; //一路往下加
        x -= lowbit(x);
    }
    return s; //返回区间和
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0); //玄学
    int a, b;
    cin >> a >> b;
    add(1, a), add(2, b); //建立 2 个节点
    cout << sum(2) << endl; //求 1~2 的区间和
    return 0;
}