HDU4737 A Bit Fun 位運算

A Bit Fun

Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2858    Accepted Submission(s): 1414


Problem Description
There are n numbers in a array, as a0, a1 ... , an-1, and another number m. We define a function f(i, j) = ai|ai+1|ai+2| ... | aj . Where "|" is the bit-OR operation. (i <= j)
The problem is really simple: please count the number of different pairs of (i, j) where f(i, j) < m.
 

Input
The first line has a number T (T <= 50) , indicating the number of test cases.
For each test case, first line contains two numbers n and m.(1 <= n <= 100000, 1 <= m <= 230) Then n numbers come in the second line which is the array a, where 1 <= ai <= 230.
 

Output
For every case, you should output "Case #t: " at first, without quotes. The t is the case number starting from 1.
Then follows the answer.
 

Sample Input
2 3 6 1 3 5 2 4 5 4
 

Sample Output
Case #1: 4 Case #2: 0
 

Source


題意:告訴n是數,求一個i到j( i<=j )的序列的或,得到的結果小於m,問這樣的序列有多少

思路:每次加入一個數,若大於等於m,那麼從當前序列開頭開始刪除數字,le指向開頭數字對應的序號,i爲當前序列末尾位置,開頭那個數字對後面造成的影響爲 i-le  。在加上最後le到n的可行序列。


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int n,m,T;
int num[33];
int a[100009];

int main()
{
    scanf("%d",&T);
    int ca=1;
    while(T--)
    {
        scanf("%d%d",&n,&m);

        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }

        memset(num,0,sizeof num);
        int tmp=0,le=0,ans=0;
        for(int i=0; i<n; i++)
        {
            tmp|=a[i];
            for(int j=0; j<30; j++) //加入當前位置上數的影響
                if((1<<j) & a[i])
                    num[j]++;

            while(le<=i && tmp>=m)
            {
                ans+=i-le;
                for(int j=0; j<30; j++)
                    if((1<<j)&a[le])
                    {
                        num[j]--;
                        if(num[j]==0)
                            tmp^=(1<<j);
                    }
                    le++;
            }
        }
        for(int i=le;i<n;i++)  //結尾還有連續可加入的部分
            ans+=n-i;
        printf("Case #%d: %d\n",ca++,ans);

    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章