acdream 1023 xor按位思考

思路:记答案为ans,统计出数列A和B在某二进制某一位上有多少个1,如果个数相同,则ans那一位上为0(因为题目要求最小的满足条件的值),如果不一样(则需要考虑那一位上异或个1),则判断数列A在那一位上0的个数是否等于数列B那一位上1的个数,不等于则无解,否则,那一位上set为1,继续判断。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 const int N = 31;
 7 int cnt1[N];
 8 int cnt2[N];
 9 
10 void decompose( int num, int * a )
11 {
12     int p = 0;
13     while ( num )
14     {
15         p++;
16         if ( num & 1 )
17         {
18             a[p]++;
19         }
20         num >>= 1;
21     }
22 }
23 
24 int main ()
25 {
26     int n, tmp;    
27     while ( scanf("%d", &n) != EOF )
28     {
29         memset( cnt1, 0, sizeof(cnt1) );
30         for ( int i = 0; i < n; i++ )
31         {
32             scanf("%d", &tmp);
33             decompose( tmp, cnt1 );
34         }
35         memset( cnt2, 0, sizeof(cnt2) );
36         for ( int i = 0; i < n; i++ )
37         {
38             scanf("%d", &tmp);
39             decompose( tmp, cnt2 );
40         }
41         int ans = 0;
42         bool flag = true;
43         for ( int i = 1; i < N; i++ )
44         {
45             if ( cnt1[i] == cnt2[i] ) continue;
46             if ( cnt1[i] + cnt2[i] == n )
47             {
48                 ans += ( 1 << ( i - 1 ) );
49             }
50             else
51             {
52                 flag = false;
53                 break;
54             }
55         }
56         if ( !flag )
57         {
58             ans = -1;
59         }
60         printf("%d
", ans);
61     }
62     return 0;
63 }
原文地址:https://www.cnblogs.com/huoxiayu/p/4694590.html