Skip to content

Commit d53ab06

Browse files
authored
solution to CHANDF.cpp
1. https://www.youtube.com/watch?v=-F7cHQ-gWS4 2. Greediest Competitive Programming problem ever 3. Awesome Logical Reasoning / Problem Solving skills are needed to solve this.
1 parent d16635b commit d53ab06

File tree

1 file changed

+122
-0
lines changed

1 file changed

+122
-0
lines changed
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Video Explanation at https://www.youtube.com/watch?v=-F7cHQ-gWS4
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
#define ll long long
6+
7+
ll f(ll &x, ll &y, ll &z) {
8+
return (x&z) * (y&z);
9+
}
10+
11+
class Bit{
12+
ll x;
13+
int _bits; // we need only these many bits, in this case 40
14+
15+
#define mask(b) (1LL<<(_bits-b)) // remember 0th bit is actually 39th bit
16+
public:
17+
Bit() {}
18+
19+
Bit(ll &y, int bits=40) {
20+
init(y, bits);
21+
}
22+
23+
void init(ll &y, int bits=40) {
24+
x = y;
25+
_bits = bits-1;
26+
}
27+
28+
bool get(int &b) {
29+
return (x & mask(b)) != 0;
30+
}
31+
32+
void set(int &b) {
33+
x |= mask(b);
34+
}
35+
36+
void reset(int &b) {
37+
if(get(b))
38+
x ^= mask(b);
39+
}
40+
41+
void set(int &b,int k) {
42+
if(k == 1) {
43+
set(b);
44+
}
45+
else {
46+
reset(b);
47+
}
48+
}
49+
50+
ll toInt() {
51+
return x;
52+
}
53+
} bitX, bitY;
54+
55+
vector<ll> getValidZValues(ll &L, ll &R) {
56+
vector<ll> validZ = {L, R}; // L and R are always valid Z values we should handle
57+
Bit bitL(L);
58+
Bit bitR(R);
59+
int k = 0;
60+
while(k<40 and bitL.get(k) == bitR.get(k)) k++;
61+
62+
for(int l = k+1; l < 40; l++) {
63+
if(bitL.get(l) != 0) continue;
64+
Bit z(L);
65+
z.set(l);
66+
for(int i=l+1; i<40; i++) {
67+
if(bitX.get(i) == 0 and bitY.get(i) == 0) {
68+
z.set(i, 0); // minimize Z
69+
}
70+
else {
71+
z.set(i, 1); // maximize F(X,Y,Z)
72+
}
73+
}
74+
validZ.push_back(z.toInt());
75+
}
76+
for(int r = k+1; r < 40; r++) {
77+
if(bitR.get(r) != 1) continue;
78+
Bit z(R);
79+
z.reset(r);
80+
for(int i=r+1; i<40; i++) {
81+
if(bitX.get(i) == 0 and bitY.get(i) == 0) {
82+
z.set(i, 0);
83+
}
84+
else {
85+
z.set(i, 1);
86+
}
87+
}
88+
validZ.push_back(z.toInt());
89+
}
90+
91+
sort(validZ.begin(), validZ.end());
92+
return validZ;
93+
}
94+
95+
int main() {
96+
ios_base::sync_with_stdio(0);
97+
int t;
98+
cin >> t;
99+
100+
while(t--) {
101+
ll x, y, l, r;
102+
cin >> x >> y >> l >> r;
103+
104+
bitX.init(x);
105+
bitY.init(y);
106+
107+
vector<ll> Zcandidates = getValidZValues(l, r);
108+
109+
ll mx = -1, ans = r;
110+
for(ll z: Zcandidates) {
111+
ll currentF = f(x, y, z);
112+
if(currentF > mx) {
113+
mx = currentF;
114+
ans = z;
115+
}
116+
}
117+
118+
cout << ans << endl;
119+
}
120+
121+
return 0;
122+
}

0 commit comments

Comments
 (0)