CodeForces 165E Compatible Numbers (dp)
2017-08-30 17:31
453 查看
题意:给你n个数,让你找到一个任意a[j]使得 a[j] & a[i] == 0,不存在输出-1。
思路:我们可以知道a[i]&(M^a[i])一定为0,(M为二进制全为1),当然a[i]不仅仅只和M^a[i]与运算后为0,M^a[i]的二进制中还有许多位为1,那么这些变为0,也是可以作为答案的。所以可以dp递推处理,见代码。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e7+5;
int n, dp[maxn], a[maxn];
int main(void)
{
while(cin >> n)
{
memset(dp, 0, sizeof(dp));
int M = (1<<23)-1;
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
dp[M^a[i]] = a[i];
}
for(int i = M; i >= 0; i--)
{
if(!dp[i])
{
for(int j = 0; j < 23; 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) puts("");
else printf(" ");
}
}
return 0;
}
思路:我们可以知道a[i]&(M^a[i])一定为0,(M为二进制全为1),当然a[i]不仅仅只和M^a[i]与运算后为0,M^a[i]的二进制中还有许多位为1,那么这些变为0,也是可以作为答案的。所以可以dp递推处理,见代码。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e7+5;
int n, dp[maxn], a[maxn];
int main(void)
{
while(cin >> n)
{
memset(dp, 0, sizeof(dp));
int M = (1<<23)-1;
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
dp[M^a[i]] = a[i];
}
for(int i = M; i >= 0; i--)
{
if(!dp[i])
{
for(int j = 0; j < 23; 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) puts("");
else printf(" ");
}
}
return 0;
}
相关文章推荐
- CodeForces - 165E(状态压缩dp)
- CodeForces - 219D Choosing Capital for Treeland——树形dp
- Obsessive String - CodeForces 494 B KMP+dp
- Codeforces 811C Vladik and Memorable Trip[dp]
- codeforces_456C_dp
- [dp] Codeforces 429B B. Working out
- Codeforces 67C. Sequence of Balls DP!
- Codeforces 629D Babaei and Birthday Cake(树状数组优化dp)
- !codeforces 399D Painting The Wall-概率dp
- codeforces 341C Iahub and Permutations(组合数dp)
- 【Codeforces 743D】 Chloe and pleasant prizes【树形dp】
- codeforces 626F DP 如何设置状态,方便转移
- CodeForces - 711C Coloring Trees(DP)(思维)
- codeforces 560E Lucas定理+dp
- CodeForces 149D Coloring Brackets 区间DP
- CodeForces 132C Logo Turtle 四维DP 递推
- codeforces 505C Mr. Kitayuta, the Treasure Hunter(DP)
- Cipher CodeForces - 156C(dp)
- CodeForces 543A Writing Code(DP)
- 【CodeForces】919B- Substring 图论,dp