Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <string>
- /**
- * Verifica daca toate caracterele din block sunt egale cu bit.
- */
- bool allOf(const std::string & block, char bit) {
- for(const auto & c : block) {
- if (c != bit) return false;
- }
- return true;
- }
- /**
- * Neaga bitul bit.
- */
- char rev(char bit) {
- return bit == '0' ? '1' : '0';
- }
- /*
- * Codeaza blocul code care ar trebui sa aiba lungimea maxima blockLength, folosind codul bit.
- */
- std::string encode(const std::string & code, uint32_t blockLength, char bit) {
- std::string result;
- result.push_back(bit);
- for(uint32_t i = 0; i < code.length(); i += blockLength) {
- std::string currentBlock = code.substr(i, blockLength);
- if(currentBlock.length() != blockLength || !allOf(currentBlock, bit)) {
- result += rev(bit) + currentBlock;
- } else {
- result += bit;
- }
- }
- return result;
- }
- int main() {
- uint32_t length;
- uint32_t block;
- std::cin >> length >> block;
- std::string bits;
- /* Si citeste caracter cu caracter si se concateneaza in string-ul bits.*/
- while(length--) {
- char bit;
- std::cin >> bit;
- bits.push_back(bit);
- }
- std::string option1 = encode(bits, block, '0');
- std::string option2 = encode(bits, block, '1');
- /* Alegem varianta mai buna */
- if(option2.length() < option1.length()) {
- option1 = option2;
- }
- /* Se afiseza raportul de compresie si apoi secventa codata, caracter cu caracter */
- std::cout << std::setprecision(2) << std::fixed << (double)bits.length() / option1.length() << std::endl;
- for(const auto & c : option1) std::cout << c << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement