您的位置:首页 > 其它

一种编码方法,附解码程序

2009-09-30 21:16 141 查看
面试时遇到的一道题目,编码与解码后数据如下:

38 1 21 2 31 3 22 4 36 5 23 6 32 7 24 8 40 9 25 10 33 11 26 12 37 13 27 14 34 15 28 16 39 17 29 18 35 19 30 20

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
请按任意键继续. . .

#include <cstdlib>
#include <iostream>
#include <vector>

#define MaxNum 40
using namespace std;
void Encode(int*Coded);
void Decode(int*Coded,int *Decoded);
int main(int argc, char *argv[])
{
int Coded[MaxNum]={0};
int decoded[MaxNum]={0};
Encode(Coded);
for(int i=0;i<MaxNum;i++)
{
cout<<Coded[i] <<" ";
}
cout<<endl;
Decode(Coded,decoded);
for(i=0;i<MaxNum;i++)
{
cout<<decoded[i] <<" ";
}
cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}

void Encode(int*Coded)
{
vector<int> v;

for(int i=0;i<MaxNum;i++)
{
v.push_back(i);
}
int front;
int num=1;
while(!v.empty())
{
front=v.front();
v.erase(v.begin());
v.push_back(front);
if(!v.empty())
{
Coded[v.front()]=num;
v.erase(v.begin());
num++;
}
}
}
void Decode(int*Coded,int* Decoded)
{
vector<int> v;

for(int i=0;i<MaxNum;i++)
{
v.push_back(Coded[i]);
}
int front;
int index=0;
while(!v.empty())
{
front=v.front();
v.erase(v.begin());
v.push_back(front);
if(!v.empty())
{
Decoded[index]=v.front();
index++;
v.erase(v.begin());
}
}
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: