二分查找 BestCoder Round #42 1002 Gunner II

本文探讨了在大型数据集上进行高效数据查询的技术,通过利用树形结构和排序算法,实现快速定位特定数据元素。文章详细介绍了如何使用lower_bound()函数在有序数组中查找指定高度的第一棵树,并在查询后更新数据结构状态。适用于需要频繁查询和维护大量数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

题目传送门

 1 /*
 2     题意:查询x的id,每次前排的树倒下
 3     使用lower_bound ()查找高度,f[i]记录第一棵高度为x树的位置,查询后+1(因为有序)
 4 */
 5 #include <cstdio>
 6 #include <algorithm>
 7 #include <cstring>
 8 using namespace std;
 9 
10 const int MAXN = 1e5 + 10;
11 const int INF = 0x3f3f3f3f;
12 struct A
13 {
14     int v, id;
15     bool operator < (const A &x) const
16     {
17         if (v == x.v)    return id < x.id;
18         return v < x.v;
19     }
20 }a[MAXN];
21 int h[MAXN], f[MAXN];
22 
23 inline int read(void)
24 {
25     int x = 0, f = 1;    char ch = getchar ();
26     while (ch < '0' || ch > '9')    {if (ch == '-') f = -1;    ch = getchar ();}
27     while (ch >='0' && ch <= '9')    {x = x * 10 + ch - '0';    ch = getchar ();}
28     return f * x;
29 }
30 
31 int main(void)        //HDOJ 5233 Gunner II
32 {
33     int n, q;
34     while (scanf ("%d%d", &n, &q) == 2)
35     {
36         for (int i=1; i<=n; ++i)    {a[i].v = read ();    a[i].id = i;}
37         sort (a+1, a+1+n);
38         for (int i=1; i<=n; ++i)
39         {
40             f[i] = i;    h[i] = a[i].v;
41         }
42         while (q--)
43         {
44             int x, p;    scanf ("%d", &x);
45             p = lower_bound (h+1, h+1+n, x) - h;
46             if (h[f[p]] != x)    {puts ("-1");    continue;}
47             printf ("%d\n", a[f[p]].id);
48             f[p]++;
49         }
50     }
51 
52     return 0;
53 }
54 
55 /*
56 5 5
57 1 2 3 4 1
58 1 3 1 4 2
59 */

 

转载于:https://www.cnblogs.com/Running-Time/p/4534490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值