Running Length Code

来源:互联网 发布:免费头像源码 编辑:程序博客网 时间:2024/05/18 22:10

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 = ||