Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:
- She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .
- Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .
For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.
Input
The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones.
The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.
Output
Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.
Examples
6
6 4 2 7 2 7
3
2 3 6
1 3 4
1 1 6
24
9
28
4
5 5 2 3
10
1 2 4
2 1 4
1 1 1
2 1 4
2 1 2
1 1 1
1 3 3
1 1 3
1 4 4
1 2 2
10
15
5
15
5
5
2
12
3
5
Note
Please note that the answers to the questions may overflow 32-bit integer type.
题意:给定一个序列,询问两个问题:1.求该序列从l到r的和 2.求该序列排序后从l到r的和
思路:乍一看是不是超简单?只是第二个问题需要排个序而已,事实证明这样会超时,是因为这10^5个数据排序就很耗时间了,然后你还每次从l到r一个个遍历数据求和,效率太低;我们注意到这个题要求的是一段连续的子序列和,那么对原序列只要经过这样的处理:a[i]+=a[i-1],在求序列和的时候可以直接这样算:a[r]-a[l-1]
实现:很简单,就直接贴代码了↓
1 #include <iostream> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 6 using namespace std; 7 long long num[100010]={0}; 8 long long cp[100010]={0}; 9 int main(int argc, char** argv) { 10 int n,m,type,l,r; 11 while(scanf("%d",&n)!=EOF){ 12 for(int i=1;i<=n;i++){ 13 scanf("%lld",&num[i]); 14 cp[i] = num[i]; 15 } 16 sort(cp+1,cp+n+1); 17 for(int i=2;i<=n;i++){ 18 num[i]+=num[i-1]; 19 cp[i]+=cp[i-1]; 20 } 21 scanf("%d",&m); 22 while(m--){ 23 scanf("%d %d %d",&type,&l,&r); 24 long long result = 0; 25 if(type==1){ 26 result = num[r]-num[l-1]; 27 }else{ 28 result = cp[r]-cp[l-1]; 29 } 30 cout<<result<<endl; 31 } 32 } 33 return 0; 34 }