2021.1.23 个人rating赛补题报告

C. Short Program

1.题意

  

编写一个程序,缩短位运算的次数,但能达到相同的结果。

 

2.题解

  没有思路,看题解+学习bitset。用bitset存全1和全0的数进行一遍输入的操作,比较结果中的各位,用三个bitset分别存与运算、异或运算和或运算。如果都是0,则三个运算都是0;如果都是1,则与运算和或运算为1,异或运算为0;如果全1为0全0为1则异或为1,其余情况类比即可,输出时将bitset转换成unsigned long long类型。

3.代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 string s = "1111111111";
 4 bitset<10> a(s), b(0), t1(0), t2(0), t3(0);
 5 int n, t;
 6 string c;
 7 int main() {
 8     cin >> n;
 9     while(n--) {
10         cin >> c >> t;
11         if(c == "&") {
12             a &= t;
13             b &= t;
14         } else if(c == "|") {
15             a |= t;
16             b |= t;
17         } else {
18             a ^= t;
19             b ^= t;
20         }
21     }
22     
23     for(int i = 0; i < 10; i++) {
24         if(a[i] == 0 && b[i] == 0) {
25             t1[i] = 0;
26             t2[i] = 0;
27             t3[i] = 0;    
28         } else if(a[i] == 0 && b[i] == 1) {
29             t1[i] = 1;
30             t2[i] = 1;
31             t3[i] = 0;
32         } else if(a[i] == 1 && b[i] == 0) {
33             t1[i] = 1;
34             t2[i] = 0;
35             t3[i] = 0;
36         } else if(a[i] == 1 && b[i] == 1) {
37             t1[i] = 1;
38             t2[i] = 0;
39             t3[i] = 1;
40         }
41     }
42 
43     cout << 3 << endl;
44     cout << "& " << t1.to_ulong() << endl;
45     cout << "^ " << t2.to_ulong() << endl;
46     cout << "| " << t3.to_ulong() << endl;
47     
48     return 0;
49 }
View Code
原文地址:https://www.cnblogs.com/lvguapi/p/14340689.html