HDU4791(线段树+二分)

#include 
#include 
#include 
#include 
#include 
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
*/

你可能感兴趣的:(二分/迭代,线段树)