poj1442

树状数组

View Code
#include <iostream>
#include
<cstdlib>
#include
<cstring>
#include
<cstdio>
#include
<algorithm>
using namespace std;

#define maxn 30005

struct Elem
{
int a;
int id;
} elem[maxn];

int n, m;
int pos[maxn];
int get[maxn];
int ar[maxn];

int lowb(int t)
{
return t & (-t);
}

void add(int i, int v)
{
for (; i < maxn; ar[i] += v, i += lowb(i))
;
}

int sum(int i)
{
int s = 0;
for (; i > 0; s += ar[i], i -= lowb(i))
;
return s;
}

bool operator <(const Elem &a, const Elem &b)
{
return a.a < b.a;
}

void input()
{
scanf(
"%d%d", &m, &n);
for (int i = 0; i < m; i++)
{
scanf(
"%d", &elem[i].a);
elem[i].id
= i;
}
for (int i = 0; i < n; i++)
scanf(
"%d", &get[i]);
}

bool ok(int x, int a)
{
return sum(x) >= a;
}

int binarysearch(int a)
{
int l = 1;
int r = m;
while (l < r)
{
int mid = (l + r) / 2;
if (ok(mid, a))
r
= mid;
else
l
= mid + 1;
}
return l;
}

void work()
{
for (int i = 0; i < m; i++)
pos[elem[i].id]
= i + 1;
int s = 0;
int x = 0;
for (int i = 0; i < n; i++)
{
for (int j = s; j < get[i]; j++)
add(pos[j],
1);
s
= get[i];
x
++;
printf(
"%d\n", elem[binarysearch(x) - 1].a);
}
}

int main()
{
//freopen("t.txt", "r", stdin);
input();
sort(elem, elem
+ m);
work();
return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/2161571.html