HDU4791(线段树+二分)

本文介绍了一段使用C++实现的高效查找与计算代码片段,包括建立树状结构进行快速查找和优化计算过程。适用于需要频繁进行查找和计算操作的场景。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 111111
#define INF 1000000009
#define pl c<<1
#define pr (c<<1)|1
#define lson tree[c].l,tree[c].mid,c<<1
#define rson tree[c].mid+1,tree[c].r,(c<<1)|1

int n, m;
long long s[maxn], p[maxn];
long long q;
struct node {
    int l, r, mid;
    long long num;
}tree[maxn<<4];

void build_tree (int l, int r, int c) {
    tree[c].l = l, tree[c].r = r, tree[c].mid = (l+r)>>1;
    if (l == r) {
        tree[c].num = s[r+1]*p[r+1];
        return ;
    }
    build_tree (lson);
    build_tree (rson);
    tree[c].num = min (tree[pl].num, tree[pr].num);
}

long long query (int l, int r, int c, int x, int y) {
    long long ans = 0;
    if (x == l && y == r) {
        ans = tree[c].num;
        return ans;
    }
    else if (y <= tree[c].mid) {
        return query (lson, x, y);
    }
    else if (x > tree[c].mid) {
        return query (rson, x, y);
    }
    else return min (query (lson, x, tree[c].mid), query (rson, tree[c].mid+1, y));
}

int main () {
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%d%d", &n, &m);
        for (int i = 1; i <= n; i++) {
            scanf ("%lld%lld", &s[i], &p[i]);
        }
        if (n > 1)
            build_tree (1, n-1, 1);
        for (int i = 1; i <= m; i++) {
            scanf ("%lld", &q);
            int pos = upper_bound (s+1, s+1+n, q) - s;
            pos--;
            if (pos == n) {
                printf ("%lld\n", p[pos]*q);
                continue;
            }
            else
                printf ("%lld\n", min (p[pos]*q, query (1, n-1, 1, pos, n-1)));
        }
    }
    return 0;
}
/*
10
3 10
0 20 100 10 200 1
55 100 5
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值