您的位置:首页 > 其它

每天学习一算法系列(7) (根据上排给出十个数,在其下排填出对应的十个数)

2014-10-15 18:55 351 查看
题目:

给你10分钟时间,根据上排给出十个数,在其下排填出对应的十个数

要求下排每个数都是先前上排那十个数在下排出现的次数。

上排的十个数如下:【0,1,2,3,4,5,6,7,8,9】

举个例子,

上排数值: 0,1,2,3,4,5,6,7,8,9

下排数值: 6,2,1,0,0,0,1,0,0,0

0在下排出现了6次,1在下排出现了2次,

2在下排出现了1次,3在下排出现了0次....

题目来源于:http://topic.csdn.net/u/20101011/16/2befbfd9-f3e4-41c5-bb31-814e9615832e.html

思路一:

这样的题目有点意思,但是仔细想想,它的原型跟八皇后有点类似,都是用回溯递归的方法去一次一次尝试,直到找出正确解。

具体的想法是:不断的去从下排数组中捉取在上排数组中对应位置中出现的个数,如果个数不对就更新下排数组中对应的值,只到找到正确值。(下排数组先初始为任意值)

如:

上排数组A:0,1,2,3,4,5,6,7,8,9

下排数组B:0,1,2,3,4,5,6,7,8,9

从上牌数组Index = 0开始,A[0] = 0,0在下排数组中的个数为1,那么下排数组B此时就要更新为:1,1,2,3,4,5,6,7,8,9,

Index = 1, A[1] = 1, 1在下排数组中的个数为2,那么下排数组B此时就要更新为:1,2,2,3,4,5,6,7,8,9,从此不断的往下进行,只要找不到正确值就一直往下进行,如果Index >= 数组长度时,那么重新恢复Index = 0再往下进行测试直到找出正确解。

代码如下:

[cpp] view
plaincopy

/*====================================

Copyright by July 2010年10月18日

Modified by yuucyf. 2011.04.28

======================================*/

#define MAX_LEN 10

class C_NumberTB

{

private:

int m_aryTop[MAX_LEN];

int m_aryBottom[MAX_LEN];

bool m_success;

public:

C_NumberTB();

public:

int* GetBottom();

void SetNextBottom();

int GetFrequecy(int nValue);

};

C_NumberTB::C_NumberTB()

{

m_success = false;

//format top

for(int i = 0; i < MAX_LEN; i++)

{

m_aryTop[i] = i;

m_aryBottom[i] = i;

}

}

int* C_NumberTB::GetBottom()

{

int i = 0;

while(!m_success)

{

i++;

SetNextBottom();

}

return m_aryBottom;

}

//set next bottom

void C_NumberTB::SetNextBottom()

{

bool bRet = true;

for(int i = 0; i < MAX_LEN; i++)

{

int nFreq = GetFrequecy(i);

if(m_aryBottom[i] != nFreq)

{

m_aryBottom[i] = nFreq;

bRet = false;

}

}

m_success = bRet;

}

//get frequency in bottom

int C_NumberTB::GetFrequecy(int nValue) //此处的nValue 即指上排的数i

{

int nCnt = 0;

for(int i = 0; i < MAX_LEN; i++)

{

if(m_aryBottom[i] == nValue)

nCnt++;

}

return nCnt; //nCnt 即对应nFreq

}

int _tmain(int argc, _TCHAR* argv[])

{

C_NumberTB objTB;

int* pResult = objTB.GetBottom();

for(int i= 0 ;i < MAX_LEN; i++)

{

cout << *pResult++ << endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐