Hdu 4217 Data Structure?【二分+树状数组】
2017年07月28日 16:06:04
阅读数:221
Data Structure?
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3359 Accepted Submission(s): 1077
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.
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
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
Author
iSea@WHU
Source
#include<iostream>
#include<algorithm>
#include<string>
#include<map>//int dx[4]={0,0,-1,1};int dy[4]={-1,1,0,0};
#include<set>//int gcd(int a,int b){return b?gcd(b,a%b):a;}
#include<vector>
#include<cmath>
#include<stack>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
#define mod 1e9+7
#define ll long long
#define maxn 400005
#define MAX 1000000000
#define ms memset
using namespace std;
ll sum[maxn];
ll n,k,x;
/*
题目大意:给定1到n的序列数,
k次删除,每次删除第m小的数,记录删数的和。
树状数组对每个位置权重设为1,
然后初始化树状数组。
不断的对树状数组进行二分查找,
查找成功后进行删除因子操作,
与树状数组概念和性质类似。
有个吐槽的地方,
序列前缀和数组不保证所有元素
全部一样(体会),但保证可以用二分,
所以在二分过程中要取其下界。
*/
int lowbit(int x) {return x&(-x); }
int Sum(int x)
{
int res=0;
for(;x>0;res+=sum[x],x-=lowbit(x));
return res;
}
void add(int x,int d)
{
for(;x<=n;sum[x]+=d,x+=lowbit(x));
}
int main()
{
int t;scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
ll ans=0;
scanf("%d%d",&n,&k);
memset(sum,0,sizeof(sum));
for(int i=1;i<=n;i++) add(i,1);
for(int i=1;i<=k;i++)
{
scanf("%d",&x);
int l=1,r=n;
int pos=-1;
while(r>=l)
{
int mid=(l+r)>>1;
int tp=Sum(mid);
if(tp>=x)
{
if(tp==x) pos=mid;///不断的找下界,,,序列中有相同的元素(但保证不递减),所以下界一定是安全的
r=mid-1;
}
else l=mid+1;
}
if(pos==-1) continue;
else ans+=pos,add(pos,-1);
}
printf("Case %d: %lld\n",ca,ans);
}
return 0;
}