编程练习|子数组求和询问

题目

Description
One day, you find an array a[N](N ≤ 50000), each element a[i] ≤ 1000000 (1 ≤ i ≤ N). We define a function v[i,j] as the sum of different value from i to j.

<> For example, N = 8, and array a[N] is 1 2 1 4 3 4 4 4.
v[1,1] = a[1] = 1
v[1,2] = a[1]+a[2] = 3
v[1,3] = a[1]+a[2] = 3 (because a[1] = a[3], so, we need to calculate either a[1]+a[2] or a[2]+a[3])
v[6,8] = 4 (because a[6] = a[7] = a[8], we just need to calculate one of them)
Now, give you an array, and m (m <= 200000) queries. Each query contains two integer i and j. For each query, you need to output v[i,j] in one line.

Input
First line is T, means there are T cases.

Each case contains an integer N(N ≤ 50000), means there are N numbers in this array.

Then N integers a[i], (1 ≤ i ≤ n)

The next line gives an integer m(m <= 200000), followed by m lines. Each line contains two integers i and j (1 ≤ i ≤ j ≤ N).

Output
For each query, output the v[i, j] in one line.

Sample Input

1
4
1 2 1 3
2
1 4
2 3
Sample Output

6
3

思路

通过设立标识判断当前数值是否被计入综合

代码

#include< iostream>
#include<string.h>
using namespace std;
const int N = 1000;
int a[N];
bool b[N];

int querySum(int* a, bool* b, int low, int high) {
	int sum = 0;
	for (int i = 1; i <= high; i++) {
		b[i] = false;
	}
	for (int i = low; i <= high; i++) {
		if (b[a[i]] == false) {
			b[a[i]] = true;
			sum += a[i];
		}
	}
	return sum;
}
int main() {
	int T, n, m,low,high;
	cin >> T;
	while (T--) {
		cin >> n;
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
		}
		cin >> m;
		while (m--) {
			cin >> low >> high;
			cout << querySum(a, b, low, high) << endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值