Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
The first line contains an integer n (1 ≤ n ≤ 5·105) — the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≤ xi ≤ 1023.
Output an integer k (0 ≤ k ≤ 5) — the length of your program.
Next k lines must contain commands in the same format as in the input.
3 | 3 ^ 2 | 1
2 | 3 ^ 2
3 & 1 & 3 & 5
1 & 1
3 ^ 1 ^ 2 ^ 3
0
You can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
题意:对一个数其进行n次位运算操作,每次操作就是位运算符+另一个数,要求把n个操作缩减到5个以内,使得两种操作后的结果不变。
思路:
&:对应位均为1运算结果对应位为1
|: 对应位有一个为1运算结果对应位为1
^:对应位不相同则运算结果对应位为1
位运算符针对每一位进行操作,二进制每位上的数只有0和1两种可能,即初始状态时每位上只可能为1或0
所以考虑所有情况时变化只有四种
一:
0 - > 0
1 - > 1
可达到这样变化的操作:&1 、 ^0 、 |0
二:
0 - > 0
1 - > 0
可达到这样变化的操作:&0
三:
0 - > 1
1 - > 1
可达到这样变化的操作:|1
四:
0 - > 1
1 - > 0
可达到这样变化的操作:^1
所以只要同时有&、|、^三种位运算就可以得到所有的变化
可以得到在每一位上需要的是什么操作,以及对应的另一个数在该位置上是0还是1
设两个数,0和1023 其中一个为(0000000000)2 另一个为 (1111111111)2
可以判断该位置是0或1时经过n个操作后的变化,以求出对应的需要
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
#define LL long long
LL n,x,fill_1 = 1023,fill_0 = 0;
char ope;
int main()
{
scanf("%lld",&n);
for(int i=0;i<n;i++){
getchar();
scanf("%c %lld",&ope,&x);
if(ope=='|'){
fill_0 = fill_0 | x;
fill_1 = fill_1 | x;
}
else if(ope=='&'){
fill_0 = fill_0 & x;
fill_1 = fill_1 & x;
}
else {
fill_0 = fill_0 ^ x;
fill_1 = fill_1 ^ x;
}
}
int AND,XOR,OR,base = 1;
AND = XOR = OR = 0;
for(int i=1;i<=10;i++){
int num0 = fill_0&1;
int num1 = fill_1&1;
if(num0==0){
if(num1==1){
XOR += 0;
AND += base;
OR += 0;
}
else{
XOR += 0;
AND += 0;
OR += 0;
}
}
else {
if(num1==1){
XOR += 0;
AND += base;
OR += base;
}
else{
XOR += base;
AND += base;
OR += 0;
}
}
fill_0>>=1;fill_1>>=1;
base<<=1;
}
printf("3\n^ %d\n& %d\n| %d\n",XOR,AND,OR);
return 0;
}