Skip to content

Commit 39f003c

Browse files
Add files via upload
1 parent d3a7272 commit 39f003c

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
We want all x that satisfy the following equation -
2+
3+
a - x = a^x
4+
5+
Let us look at a from the last bit onwards
6+
7+
Suppose the last bit of a is 1, then the last bit of x can 1
8+
9+
1 - 1 = 1^1 = 0
10+
11+
It can also be 0
12+
13+
1 - 0 = 1^0 = 1
14+
15+
What if the last bit of a is 0 ?
16+
17+
Then last bit of x can be 0
18+
19+
0 - 0 = 0^0 = 0
20+
21+
Suppose the last bit of a is 0 and the last bit of x is 1. What happens ?
22+
23+
Let us look at the leftmost 1 in a. All the bits till this leftmost 1 are toggled.
24+
25+
For example if fifth bit is the leftmost 1 and after that there are 4 0s.
26+
27+
If we subtract 1 from the first bit, the the other four bits in A are toggled.
28+
29+
Now whatever the value of x is for bits 2, 3, 4, 5 ... A - x cannot be equal to A^x because the bits of A are different here now.
30+
31+
---------------
32+
33+
Hence, there are two possibilites for every 1 and only one possibility for every 0.
34+
35+
---------------------------------------------
36+
37+
void solve()
38+
{
39+
int n;
40+
scanf("%d", &n);
41+
42+
long long no_of_ways = 1;
43+
44+
while(n)
45+
{
46+
if(n%2 == 1)
47+
no_of_ways = no_of_ways << 1;
48+
49+
n = n >> 1;
50+
}
51+
52+
printf("%I64d\n", no_of_ways);
53+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
It is always optimal to print chunks of each character together.
2+
3+
(One way of doing this is by simply sorting the string.)
4+
5+
-----------
6+
7+
Why is it optimal ?
8+
9+
Every palindrome will have at least two characters.
10+
11+
Suppose a certain character occurs f times.
12+
13+
Then it can be involved in at most C(f, 2) + C(f, 1) = f(f + 1)/2 palindromes.
14+
15+
We get C(f, 2) whenever this character is the end points of any palindrome
16+
We get C(f, 1) whenever we have a 1-character palindrome.
17+
18+
19+
When they are all printed together there will be f(f + 1)/2 palindromes.
20+
21+
Palindrome of length 1, 2, 3, ... , f
22+
23+
-----------------------------
24+
25+
int main()
26+
{
27+
string S;
28+
int length;
29+
cin >> length >> S;
30+
31+
sort(S, S + length);
32+
printf("%s\n", S);
33+
return 0;
34+
}

0 commit comments

Comments
 (0)