首页 > 代码库 > hdu 4737 A Bit Fun(TwoPointer)

hdu 4737 A Bit Fun(TwoPointer)

题目链接;hdu 4737 A Bit Fun

题目大意:给定一个长度为n的序列,现在问说有多少对i,j满足 f(i,j)<m.

解题思路: Twopointer,将每个数拆分成二进制形式,然后维护连个指针l,r,保证f(l, r) < m,那么当i = l时,对应的j就有r - l + 1种选择方法。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
const int maxn = 100005;

int c[35], arr[maxn];

int add (int x, int v) {
    int ret = 0;
    for (int i = 0; i <= 30; i++) {
        if (x&(1<<i))
            c[i] += v;

        if (c[i])
            ret |= (1<<i);
    }
    return ret;
}

ll solve () {
    ll ret = 0;
    memset(c, 0, sizeof(c));
    int l = 0, n, m, x, s = 0;

    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        s = add(arr[i], 1);

        while (s >= m)
            s = add(arr[l++], -1);
        ret += (i - l + 1);
    }
    return ret;
}

int main () {
    int cas;
    scanf("%d", &cas);
    for (int kcas = 1; kcas <= cas; kcas++) {
        ll ans = solve();
        printf("Case #%d: %I64d\n", kcas, ans);
    }
    return 0;
}

hdu 4737 A Bit Fun(TwoPointer)