#include "encoder.h"
#include "encoderlib.h"
#include <bits/stdc++.h>
using namespace std;
string convert(int num){
string s = "";
for(int j = 7; j >= 0; j--){
if(num >= pow(2, j)){
num -= pow(2, j);
s += '1';
}
else s += '0';
}
return s;
}
void encode(int N, int M[])
{
int n = N;
// break each number into 8-byte strings
string all_nums;
for(int i = 0; i < n; i++) all_nums += convert(M[i]);
// see the total cost for each encoding scheme
int normal = 0;
int flipped = 0;
bool scheme = false;
for(int i = 0; i < all_nums.size() - 1; i += 2){
int val = 0;
if(all_nums[i] == '1') val += 1;
if(all_nums[i + 1] == '1') val += 2;
normal += val;
flipped += 3 - val;
}
if(flipped < normal) scheme = true;
// encode
for(int i = 0; i < all_nums.size() / 2; i++){
int val = 0;
if(all_nums[i * 2] == '1') val += 1;
if(all_nums[(i * 2) + 1] == '1') val += 2;
int amount = val;
if(scheme) amount = 3 - val;
for(int j = 0; j < amount; j++){
send(i);
}
}
if(scheme){
for(int i = 0; i < 4; i++) send(255);
}
}
#include "decoder.h"
#include "decoderlib.h"
#include <bits/stdc++.h>
using namespace std;
int convert(string& s, int l, int r){
int res = 0;
string thing ="";
for(int i = r; i >= l; i--) thing += s[i];
for(int i = 0; i <= 7; i++){
if(thing[i] == '1') res += pow(2, (i));
}
return res;
}
void decode(int N, int L, int X[])
{
int n = N;
vector<string> ref = {"00", "10", "01", "11"};
map<int, int> freq;
bool flipped = false;
for(int i = 0; i < L; i++){
freq[X[i]]++;
}
string s;
for(int i = 0; i < N; i++){
s += "00000000";
}
if(freq[255] >= 4){
flipped = true;
freq[255] -= 4;
}
for(int i = 0; i < s.size() / 2; i++){
int amount = freq[i];
if(flipped) amount = 3 - amount;
string good = ref[amount];
int ind = i * 2;
s[ind] = good[0];
s[ind + 1] = good[1];
}
// convert back to decimal
for(int i = 0; i < n; i++){
int num = convert(s, i * 8, (i + 1) * 8 - 1);
output(num);
}
}