using
System;
using
System.Collections.Generic;
public
class
PriorityQueue<T> {
private
List<T> heap;
private
Comparison<T> comparison;
public
PriorityQueue(Comparison<T> comparison)
{
this
.heap =
new
List<T>();
this
.comparison = comparison;
}
public
void
Enqueue(T item)
{
this
.heap.Add(item);
HeapifyUp(
this
.heap.Count - 1);
}
public
T Dequeue()
{
if
(
this
.heap.Count == 0) {
throw
new
InvalidOperationException(
"Priority queue is empty."
);
}
T root =
this
.heap[0];
int
lastIndex =
this
.heap.Count - 1;
this
.heap[0] =
this
.heap[lastIndex];
this
.heap.RemoveAt(lastIndex);
HeapifyDown(0);
return
root;
}
public
T Peek()
{
if
(
this
.heap.Count == 0) {
throw
new
InvalidOperationException(
"Priority queue is empty."
);
}
return
this
.heap[0];
}
public
int
Count =>
this
.heap.Count;
public
bool
IsEmpty =>
this
.heap.Count == 0;
private
void
HeapifyUp(
int
index)
{
while
(index > 0) {
int
parentIndex = (index - 1) / 2;
if
(
this
.comparison(
this
.heap[index],
this
.heap[parentIndex])
< 0) {
Swap(index, parentIndex);
index = parentIndex;
}
else
{
break
;
}
}
}
private
void
HeapifyDown(
int
index)
{
int
leftChild = 2 * index + 1;
int
rightChild = 2 * index + 2;
int
smallest = index;
if
(leftChild <
this
.heap.Count
&&
this
.comparison(
this
.heap[leftChild],
this
.heap[smallest])
< 0) {
smallest = leftChild;
}
if
(rightChild <
this
.heap.Count
&&
this
.comparison(
this
.heap[rightChild],
this
.heap[smallest])
< 0) {
smallest = rightChild;
}
if
(smallest != index) {
Swap(index, smallest);
HeapifyDown(smallest);
}
}
private
void
Swap(
int
i,
int
j)
{
T temp =
this
.heap[i];
this
.heap[i] =
this
.heap[j];
this
.heap[j] = temp;
}
}
class
GFG {
static
int
Solve(
string
s,
int
K)
{
int
N = s.Length;
PriorityQueue<Pair> pq =
new
PriorityQueue<Pair>(
(a, b) => b.xorVal - a.xorVal);
pq.Enqueue(
new
Pair(0, 0));
for
(
int
i = 0; i < N; i++) {
int
digit =
int
.Parse(s[i].ToString());
int
sz = pq.Count;
for
(
int
j = 0; j < sz; j++) {
Pair p = pq.Dequeue();
int
mask = p.mask;
int
xorVal = p.xorVal;
int
setBits = CountSetBits(mask);
if
(setBits < K) {
pq.Enqueue(
new
Pair(mask & ~(1 << setBits),
xorVal ^ digit));
}
pq.Enqueue(
new
Pair(mask & ~(0 << setBits),
xorVal));
}
}
int
ans = 0;
while
(pq.Count > 0) {
ans = Math.Max(ans, pq.Dequeue().xorVal);
}
return
ans;
}
static
int
CountSetBits(
int
n)
{
int
count = 0;
while
(n > 0) {
count += n & 1;
n >>= 1;
}
return
count;
}
class
Pair {
public
int
mask;
public
int
xorVal;
public
Pair(
int
mask,
int
xorVal)
{
this
.mask = mask;
this
.xorVal = xorVal;
}
}
public
static
void
Main(
string
[] args)
{
string
s =
"1234"
;
int
K = 1;
Console.WriteLine(Solve(s, K));
s =
"6479"
;
K = 2;
Console.WriteLine(Solve(s, K));
}
}