Data Structure?
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1726 Accepted Submission(s): 540
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题意:有序数列1-N,总共有K次取数操作,每次都取走第ki小的数,问此人取走的数的和 思路:用线段树做,用线段树的len 存储某个区间的数的个数,当查找第ki小的数的时候,看它左 子树的len值是否大于Ki,如果大于说明左子树能够容纳K个数,否则在它的右子树上
#include<stdio.h> #include<string.h> #define N 262144 struct btree { int l,r; int len; }tree[N*3]; void buildtree(int p,int left,int right) { int w,mid; tree[p].l=left; tree[p].r=right; tree[p].len=right-left+1; if(right==left) return ; mid=(left+right)>>1; w=p<<1; buildtree(w,left,mid); buildtree(w+1,mid+1,right); } int query(int p,int k) { int w; tree[p].len--; if(tree[p].l==tree[p].r) return tree[p].l; w=p<<1; if(tree[w].len>=k) return query(w,k); else return query(w+1,k-tree[w].len); } int main() { int T,n,k,i,p,cas=1; long long sum; scanf("%d",&T); while(T--) { scanf("%d %d",&n,&k); buildtree(1,1,n); for(i=1,sum=0;i<=k;i++) { scanf("%d",&p); sum+=query(1,p); } printf("Case %d: ",cas++); printf("%I64d\n",sum); } return 0; }