Powers of two(multiset的运用)

【题目】

Powers of two

B - Powers of two


Time limit : 2sec / Memory limit : 1024MB

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is Ai. He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2. Note that a ball cannot belong to multiple pairs. Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2t using some non-negative integer t.

Constraints

  • 1≤N≤2×105
  • 1≤Ai≤109
  • Ai is an integer.

Input

Input is given from Standard Input in the following format:

N
A1 A2 … AN

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls. Note that we cannot pair the second ball with itself.


Sample Input 2

5
3 11 14 5 13

Sample Output 2

2

【题解】

题意:给定长度为n的序列,输出最多的两两组合之和为2的整次方的对数。

按理说我当时也是从后往前匹配的思路啊,但是为什么wa了...谜(留个悬念)

做法就是存入序列multiset自动排序,然后从大到小寻找是否存在可匹配满足条件的项,如果存在,答案+1,并删去匹配项。

认识了新容器 --- multiset,加深了迭代器的印象(太久没用都忘了)。

【代码】

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define Pi acos(-1)
#define eps 1e-8
using namespace std;
typedef long long int ll;
const int maxn=2*1e5+5;
const ll inf=0x3f3f3f3f;
const int mod=1e9+7;
multiset <int> s;
int main()
{
    int n; scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        int x; scanf("%d",&x);
        s.insert(x);
    }
    int ans=0;
    while(!s.empty())
    {
        multiset <int> ::iterator it=s.end();
        it--;
        int x=*it;
        s.erase(it);
        for(n=1;n<=x;n*=2);
        if(s.find(n-x)!=s.end())
            ans++,s.erase( s.find(n-x) );
    }
    printf("%d\n",ans);
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值