CodeChef:Good Pairs(dp & 二进制)

You are given N integers: A1A2, ..., AN. You need to count the number of pairs of indices (ij) such that 1 ≤ i < j ≤ N and Ai | Aj ≤ max(AiAj).

Note: Ai | Aj refers to bitwise OR.

Input

  • The first line of the input contains an integer T, denoting the number of test cases. The description of each testcase follows.
  • The first line of each testcase contains a single integer: N
  • The second line of each testcase contains N integers: A1A2, ..., AN

Output

For each test case, output a single line containing the answer for that test case.

Constraints

  • 1 ≤ T ≤ 20
  • 1 ≤ N ≤ 106
  • 0 ≤ Ai ≤ 106
  • 1 ≤ Sum of N over all test cases ≤ 106


题意:給N个数字,问有多少对数满足a[i]|a[j] <= max(a[i],a[j]),i<j。
思路:首先a[i]|a[j] >= max(a[i],a[j]),于是题目变成求a[i]|a[j] == max(a[i],a[j]),若a[i]<=a[j],那么a[i]|a[j] == a[j],即a[i]为a[j]的二进制子集,那么求出每个数在这N个数里有多少个它的子集即可,sum over subsets dp复杂度O(N*2^N),N<21。
# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e6;
LL num[maxn+3], num2[maxn+3];
int main()
{
    int t, n, m;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(num, 0, sizeof(num));
        memset(num2, 0, sizeof(num));
        for(int i=0; i<n; ++i)
        {
            scanf("%d",&m);
            ++num[m];
            ++num2[m];
        }
        for(int i=0; i<21; ++i)
            for(int j=1; j<=maxn; ++j)
                if(j&(1<<i))
                    num[j] += num[j^(1<<i)];
        LL ans = 0;
        for(int i=0; i<=maxn; ++i)
        {
            if(num[i])
            {
                ans += num2[i]*(num2[i]-1)/2;
                ans += (num[i]-num2[i])*num2[i];
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值