思路:求k小与k大本质上窝觉得是一样的,可以互相转换。
http://www.cnblogs.com/wuyiqi/archive/2011/12/25/2301071.html这博客讲的还不错。
/***************************************** Author :Crazy_AC(JamesQi) Time :2015 File Name : *****************************************/ // #pragma comment(linker, "/STACK:1024000000,1024000000") #include <iostream> #include <algorithm> #include <iomanip> #include <sstream> #include <string> #include <stack> #include <queue> #include <deque> #include <vector> #include <map> #include <set> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <limits.h> using namespace std; #define MEM(a,b) memset(a,b,sizeof a) typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> ii; const int inf = 1 << 30; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; inline int Readint(){ char c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); } return x; } inline int lowbit(int x){ return x & (-x); } int bit[300000]; int n,m; LL ans; void add(int x,int v){ while(x <= n){ bit[x] += v; x += lowbit(x); } } int sum(int k){ int num = 0; int x = 0; for (int i = 18;i >= 0;i--){ if (x + (1 << i) <= n && bit[x + (1 << i)] + num < k){ x += (1 << i); num += bit[x]; } } return x + 1; } void solve(int kase){ ans = 0LL; memset(bit,0,sizeof bit); scanf("%d%d",&n,&m); for (int i = 1;i <= n;i++) add(i,1); for (int i = 0;i < m;i++){ int x; scanf("%d",&x); int tmp = sum(x); add(tmp,-1); ans += tmp; } printf("Case %d: ",kase); printf("%lld\n",ans); } int main() { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); int icase = 0; int t; scanf("%d",&t); while(t--){ solve(++icase); } return 0; }