题目链接 http://codeforces.com/problemset/problem/433/B
题意,有n颗宝石,每个宝石都有自己的价值。
然后m次询问。问区间[i,j]的宝石的总值,或者问排序后的区间[i,j]的总值。
思路:求前缀和。
sqrt(b,b+n) 平均时间复杂度为 nlog(n)
设数组a为原数组 ,aa[i] 记录了 从 a[0]+..+.a[i] 。求a[l]+....+a[r] = aa[r] - aa[l-1]
b数组为排序后的数组,bb数组同理
代码如下
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long LL;
typedef long long ll;
const int maxn = 1e6+6;
const int modn = 1e9+7;
const int INF = 0x3f3f3f3f;
char str[maxn];
ll a[maxn];
ll aa[maxn];
ll b[maxn];
ll bb[maxn];
void show(int a[],int n){
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}printf("\n");
}
int main(){
int n,t,u,v,m;
// freopen("C:\\Users\\lenovo\\Desktop\\data.in","r",stdin);
while(scanf("%d",&n)+1){
for(int i=0;i<n;i++){
scanf("%I64d",a+i);
b[i] = a[i];
}
sort(b,b+n);
aa[0] = a[0];
bb[0] = b[0];
for(int i=1;i<n;i++){
aa[i] = a[i]+aa[i-1];
bb[i] = b[i]+bb[i-1];
}
scanf("%d",&m);
while(m--){
scanf("%d%d%d",&t,&u,&v);
u--;v--;
if(t==1){
printf("%I64d\n",aa[v]-aa[u-1]);
}else{
printf("%I64d\n",bb[v]-bb[u-1]);
}
}
}
}