动态规划——Compatible Numbers
来源:互联网 发布:天猫跟淘宝有啥区别 编辑:程序博客网 时间:2024/06/06 00:16
Two integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.
You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.
The first line contains an integer n (1 ≤ n ≤ 106) — the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 4·106) — the elements of the given array. The numbers in the array can coincide.
Print n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.
290 36
36 90
43 6 3 6
-1 -1 -1 -1
510 6 9 8 2
-1 8 2 2 8
题意:给n个数,对于某个数a[i]如果有a[j]使a[i]&a[j]==0,则对于a[i]对应a[j],否则对应-1。要求输出每个数所对应的数。如果有多种情况输出其中一种即可。
思路:最容易想到的是对每个数在数组中遍历寻找,但是无疑会TLE。。。
于是看数据知道a[i]最大为4·106
那么可以设置一个常数k=(1<<22)-1;然后用dp[i^a[i]]=a[i]保存a[i]和与k的异或的值的对应关系。
之后寻找时对每个位枚举即可。
详见代码。
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int k=(1<<22)-1;int n;int dp[k+1];int a[4000005];int main(){ while(~scanf("%d", &n)) { memset(a, 0, sizeof(a)); memset(dp, 0, sizeof(dp)); for(int i=1; i<=n; i++) { scanf("%d", &a[i]); dp[k^a[i]]=a[i]; } for(int i=k; i>=0; i--) { if(!dp[i]) //如果没有这个状态就不用判断 for(int j=0; j<22; j++) { if(dp[i|(1<<j)]) //枚举每一位是否出现过这种状态 dp[i]=dp[i|(1<<j)]; } } for(int i=1; i<=n; i++) { if(dp[a[i]]) printf("%d", dp[a[i]]); else printf("-1"); if(i==n) printf("\n"); else printf(" "); } } return 0;}
- 动态规划——Compatible Numbers
- 动态规划入门——Humble Numbers
- HDU 1058 Humble Numbers—dp动态规划基础题
- 【动态规划】Phone Numbers
- 动态规划--Humble Numbers
- UVa944 - Happy Numbers(动态规划)
- hdu1058 Humble Numbers (动态规划)
- 动态规划——357. Count Numbers with Unique Digits[medium]
- 动态规划——什么是动态规划?
- 动态规划 — LIS
- HDU 1058(Humble Numbers)动态规划
- 【动态规划】【数位DP】[SPOJ10606]Balanced numbers
- hdu 1058 Humble Numbers (动态规划)
- timus 1002. Phone Numbers(KMP&动态规划)
- 【杭电1058】Humble Numbers-动态规划
- URAL 1002|Phone Numbers|动态规划
- codeforces 165E - Compatible Numbers
- Codeforces 164 E Compatible Numbers
- mfc 对话框 孙鑫 第七章
- C++迭代子类
- 判断一棵树是否是完全二叉树
- 1.2 解压可迭代对象赋值给多个变量
- 杭电暑期多校集训—Time To Get Up
- 动态规划——Compatible Numbers
- 无向图建立 邻接表(2)
- CentOS7如何设置防火墙
- HDU6077
- [PAT乙级]1005. 继续(3n+1)猜想 (25)
- Rdd的 foreach 和 foreachPartition
- mongodb简介 安装
- POJ 2524 Ubiquitous Religions(水水的并查集)
- 如何学习JavaScript?