Data Structure?
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2001 Accepted Submission(s): 623
Problem Description
Data structure is one of the basic skills for Computer Science students, which is a particular way of storing and organizing data in a computer so that it can be used efficiently. Today let me introduce a data-structure-like problem for you.
Original, there are N numbers, namely 1, 2, 3...N. Each round, iSea find out the Ki-th smallest number and take it away, your task is reporting him the total sum of the numbers he has taken away.
Original, there are N numbers, namely 1, 2, 3...N. Each round, iSea find out the Ki-th smallest number and take it away, your task is reporting him the total sum of the numbers he has taken away.
Input
The first line contains a single integer T, indicating the number of test cases.
Each test case includes two integers N, K, K indicates the round numbers. Then a line with K numbers following, indicating in i (1-based) round, iSea take away the Ki-th smallest away.
Technical Specification
1. 1 <= T <= 128
2. 1 <= K <= N <= 262 144
3. 1 <= Ki <= N - i + 1
Each test case includes two integers N, K, K indicates the round numbers. Then a line with K numbers following, indicating in i (1-based) round, iSea take away the Ki-th smallest away.
Technical Specification
1. 1 <= T <= 128
2. 1 <= K <= N <= 262 144
3. 1 <= Ki <= N - i + 1
Output
For each test case, output the case number first, then the sum.
Sample Input
2 3 2 1 1 10 3 3 9 1
Sample Output
Case 1: 3 Case 2: 14
思路:刚开始想着可以通过求查询序列的逆序数(标准次序为从大到小),然后加上查询串的累加和,最后发现算法有问题,看了讨论区,用线段树才是王道啊。。。
#include<stdio.h>
#define N 262144
struct node{
int lc,rc,cnt;
}set[4*N];
void build(int p, int left, int right){
int v,mid;
set[p].lc=left;
set[p].rc=right;
set[p].cnt=right-left+1;
if(left==right){
return;
}
mid=(left+right)>>1;
v=p<<1;
build(v,left,mid);
build(v+1,mid+1,right);
}
int query(int p, int x){
int v,res=0;
if(set[p].lc==set[p].rc){
set[p].cnt--;
return set[p].lc;
}
v=p<<1;
if(x<=set[v].cnt)
res=query(v,x);
else
res=query(v+1,x-set[v].cnt);
set[p].cnt--;
return res;
}
int main(){
int T,n,i,k,x,index=1;
long long ans;
scanf("%d",&T);
while(T--){
scanf("%d %d",&n,&k);
build(1,1,n);
for(i=1,ans=0;i<=k;i++){
scanf("%d",&x);
ans+=query(1,x);
}
printf("Case %d: %I64d\n",index++,ans);
}
return 0;
}