昨天学习了树状数组,今天来练两道题。
题目描述
给定一个长度 n(n≤100000),初始值都为 0 的序列,x(x≤100000) 次的修改某些位置上的数字,每次加上一个数,然后提出 y(y≤100000) 个问题,求每段区间的和。
输入格式
第一行 1 个整数,表示序列的长度 n。
第二行 1 个整数,表示操作的次数 w。
后面依次是 w 行,分别表示加入和询问操作。
其中,加入用 x
表示,询问用 y
表示。
x的格式为 x a b
表示在序列上第 a 个数加上 b。保证 1≤a≤n,1≤b≤109。
y 的格式为 y a b
表示询问 a 到 b 区间的加和。保证 1≤a≤b≤n。
输出格式
每行一个正整数,分别是每次询问的结果
输入输出样例
输入 #1
5
4
x 3 8
y 1 3
x 4 9
y 3 4
输出 #1
8
17
一道树状数组的模板题,需要注意,原数组所有元素为0,其实就是不需要输入a[i]
,直接进行x,y
操作即可。
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
#define int long long
#define endl '\n'
typedef long long ll;
const int N = 100010;
int a[N],tr[N];
int lowbit(int x)
{
return x & -x;
}
//修改某点
void add(int x, int v)
{
for (int i = x; i <= N; i += lowbit(i)) tr[i] += v;
}
//求前缀和
int query(int x)
{
int res = 0;
for (int i = x; i != 0; i -= lowbit(i)) res += tr[i];
return res;
}
signed main()
{
int n, w;
cin >> n >> w;
while (w--)
{
char op;
int x,y;
cin >> op >> x >> y;
if (op == 'x')
{
add(x, y);
}
else cout << query(y) - query(x - 1) << endl;
}
return 0;
}
B. Interesting drink
题目详情
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink “Beecola”, which can be bought in n different shops in the city. It’s known that the price of one bottle in the shop i is equal to x**i coins.
Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent m**i coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of “Beecola”.
输入
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy’s favourite drink.
The second line contains n integers x**i (1 ≤ x**i ≤ 100 000) — prices of the bottles of the drink in the i-th shop.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.
Then follow q lines each containing one integer m**i (1 ≤ m**i ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
输出
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
测试用例
input
5
3 10 8 6 11
4
1
10
3
11
output
0
4
1
5
题目大意及解题思路
大意:给出若干查询,对于每个查询,输出数组中有多少个数比它小。
思路:记录每个数出现的次数,这里不可以用数组,因为每个数最大为1e9,数组放不下,用map。然后就是单点修改,区间求和的树状数组模板了。
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
#define int long long
#define endl '\n'
typedef long long ll;
const int N = 1e9;
map<int, int> m;
int lowbit(int x)
{
return x & -x;
}
void add(int x, int v)
{
for (int i = x; i <= N; i += lowbit(i)) m[i]+=v;
}
int query(int x)
{
int res = 0;
for (int i = x; i != 0; i -= lowbit(i)) res += m[i];
return res;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, w;
cin >> n ;
for (int i = 1; i <= n; i++)
{
int a;
cin >> a;
add(a,1);
}
cin >> w;
while (w--)
{
int x;
cin >> x;
cout << query(x) << endl;
}
return 0;
}