Running Length Code

本文介绍了一种用于压缩二进制字符串的运行长度编码方法,并提供了一个具体的编码程序实现示例。该方法通过查找连续的0或1序列,并将其编码为一个字节来实现压缩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FJNU.1411

Description
The running length code is a kind of compression code of binary string. A running length code for a binary string is a sequence of bytes, where each byte (1 byte=8 bit) denotes a continuous part (continuous 0’s or continuous 1’s) of the binary string, with the leftmost bit of the byte denoting the color of the part (0 or 1) and the other seven bits denoting the length of the part. Suppose that the length of any continuous part in a binary string is less than 128. Now given a binary string which length is less than 1000, write a program to encode it with the running length code.

Input
The input contains a series of test cases, and each case consists of two lines. The first line of each test case is a single integer n (1<=n<1000), representing the length of a binary string. The following line represents the binary string, with one space separating every two bits of the binary string. The last test case is followed by a line containing one 0 that terminates the input.

Output
Output one line for each test case, representing the running length code of the binary string. Each byte of the running length code is represented by an integer less than 256. Every two integers are separated by one space.

Sample Input
15 
1 0 1 0 0 0 0 0 0 0 1 1 1 1 1
0

Sample Output
129 1 129 7 133

Source
福建师范大学第三届程序设计比赛

My Program

#include<iostream>
#include
<string.h>
#define N 1000
using namespace std;

int main()
{
    
char str[N],last;
    
int n,i,con;
    
while(cin>>n)
    
{
        
if(n==0)
            
break;
        i
=0;
        
while(i<n)
        
{
            scanf(
"%c",&last);
            
if(last=='0'||last=='1')
                str[i
++]=last;
        }

        last
=str[0];con=1;
        
for(i=1;i<n;i++)
            
if(str[i]==last)
                con
++;
            
else
            
{
                
if(last=='0')
                    cout
<<con<<" ";
                
else
                    cout
<<128+con<<" ";
                last
=str[i];
                con
=1;
            }

        
if(last=='0')
            cout
<<con<<endl;
        
else
            cout
<<128+con<<endl;
    }

    
return 0;
}

YOYO's Note:
简单题。找连续的最长0/1段,然后输出每段的编码(其实就是连续长度,当是1段的时候+128)。
原来因为它是空格输入的,原来为输入字符串很伤脑筋。现在写Note的时候突然想起其实直接输入int[]不就好了么! = A = || 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值