题目
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;
}