Codeforces Round #496 (Div. 3) C. Summarize to the Power of Two(思维+map)


题目链接:http://codeforces.com/contest/1005/problem/C

       题意是给你n个数,判断这n个数中是否存在有a[i]+a[j]等于2的任意次方,如果不存在a[j]满足上述条件就删除a[i]这个数,问需要删除多少个数字。

       思路:因为数据范围是120000,所以n*n是过不了的,然后我试着优化到了n*logn,还是t了。最后ac的方法的时间复杂度是n*30,感觉很巧妙,这里我用map来记录每一个数的出现次数,然后对数组进行遍历,因为是要找这个数和另外一个数相加的和,所以我们先要让ma[pre[i]]--;意思就是先让这个数拿出来,判断过后再把这个数加上,因为pre[i]的大小是1e9的,所以首先跑了一遍2的次方,发现只用判断到2的30次方就行了,剩下的就看代码吧。


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#define ll long long
using namespace std;
int n;
int pre[120005];
map<int,int> ma;

int main()
{
	scanf("%d",&n);
  for(int i=0;i<n;i++){
    scanf("%d",&pre[i]);
    ma[pre[i]]++;
  }
  int sum = 0;
  for(int i=0;i<n;i++){
    int flag = 0;
    ma[pre[i]]--;
    for(int j=0;j<=30;j++){
      int ans = (1 << j);   // 计算2的次方
      if(ma[ans - pre[i]] != 0){
        flag = 1;
      }
    }
    ma[pre[i]]++;
    if(!flag)sum++;
  }
	printf("%d\n",sum);
	return 0;
}

全部评论

相关推荐

10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务