Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9d2876c

Browse files
Create Or Plus Max Explanation.txt
1 parent 158aa00 commit 9d2876c

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
The largest sum will always be between the two largest elements.
2+
3+
For every mask m, let us keep track of the largest and second largest element.
4+
5+
Instead of finding the two largest elements in O(bits set) time for every mask,
6+
we can instead build it by taking the two largest elements of all it's submasks.
7+
8+
------
9+
10+
We can then build a prefix maximum over this
11+
12+
------
13+
14+
void update(int n, int &largest, int &second_largest, vector <int> &A)
15+
{
16+
if(n == largest || n == second_largest)
17+
{ //cout << "Return";
18+
return;
19+
}
20+
21+
if(largest == -1 || A[n] > A[largest])
22+
{
23+
second_largest = largest;
24+
largest = n;
25+
}
26+
else if(second_largest == -1 || A[n] >= A[second_largest])
27+
{
28+
second_largest = n;
29+
}
30+
}
31+
32+
int main()
33+
{
34+
int no_of_elements;
35+
cin >> no_of_elements;
36+
37+
int max_mask = 1 << no_of_elements;
38+
vector <int> A(max_mask + 1);
39+
for(int i = 0; i < max_mask; i++)
40+
{
41+
cin >> A[i];
42+
}
43+
44+
vector <int> largest(max_mask, -1), second_largest(max_mask, -1), sum(max_mask);
45+
largest[0] = second_largest[0] = 0;
46+
for(int m = 1; m < max_mask; m++)
47+
{
48+
//cout << "At " << m << " ";
49+
update(0, largest[m], second_largest[m], A);
50+
update(m, largest[m], second_largest[m], A);
51+
52+
for(int bit = 0; bit < no_of_elements; bit++)
53+
{
54+
if(is_bit_set(m, bit))
55+
{
56+
int submask_without_this_bit = m^(1 << bit);
57+
//cout << " At old " << submask_without_this_bit << "\n";
58+
update(largest[submask_without_this_bit], largest[m], second_largest[m], A);
59+
update(second_largest[submask_without_this_bit], largest[m], second_largest[m], A);
60+
}
61+
}
62+
}
63+
64+
for(int m = 1; m < max_mask; m++)
65+
{
66+
sum[m] = max(sum[m - 1], A[largest[m]] + A[second_largest[m]]);
67+
}
68+
69+
for(int m = 1; m < max_mask; m++)
70+
{
71+
cout << sum[m] << "\n";
72+
}
73+
74+
return 0;
75+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /