數據結構與算法之枚舉(窮舉)法 C++實現
枚舉法的本質就是從所有候選答案中去搜索正確的解,使用該算法需要滿足兩個條件:
1、可以先確定候選答案的數量;
2、候選答案的范圍在求解之前必須是一個確定的集合。
枚舉是最簡單,最基礎,也是最沒效率的算法
枚舉法優點:
1、枚舉有超級無敵准確性,只要時間足夠,正確的枚舉得出的結論是絕對正確的。
2、枚舉擁有天下第一全面性,因為它是對所有方案的全面搜索,所以,它能夠得出所有的解。
程序優化:
對於枚舉算法,加強約束條件,縮小枚舉的范圍,是程序優化的主要考慮方向。
百錢買百雞:
代碼:
#include
const int COCKPR = 3;
const int HENPR = 5;
const double CHICKPR = 1/3;
void buyChicken(int money, int chooks);
int main()
{
int money = 100;
int chooks = 100;
buyChicken(money, chooks);
return 0;
}
void buyChicken(int money, int chooks)
{
using namespace std;
int MaxCock = money/COCKPR;
int MaxHen = money/HENPR;
int MaxChick = chooks;
int cock,hen,chick;
int count = 0;
for(cock=0; cock<= MaxCock; cock++)
{
for(hen=0; hen<=MaxHen; hen++)
{
for(chick=0; chick<=MaxChick; chick++)
{
if (0 == chick%3 && cock + hen + chick == chooks && COCKPR*cock + HENPR*hen + CHICKPR*chick == money)
cout << "公雞: " << cock << " 母雞: " << hen << " 小雞: " << chick << " 第 " << count << "有結果" <
運行結果:
只對小雞的數量添加一個最小的起始值
函數裡面加 int MinChick = chooks-MaxCock-MaxHen;
把最裡層小雞數量的fZ喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vctGtu7e1xMbwyrzM9bz+uMTOqtChvKbX7tChJiMyMDU0MDsgZm9yKGNoaWNrPU1pbkNoaWNrOyBjaGljazw9TWF4Q2hpY2s7IGNoaWNrJiM0MzsmIzQzOykgCtTLy+PKsbzkuLTU07bIyOfPwqGjyrG85Li01NO2yLz1ydnSu7DroaPLtcP3ttTT2sO2vtnL47eoo6y808e/1LzK+Mz1vP6jrMv10KHDtr7ZtcS3ts6no6zKx7PM0PLTxbuvtcTW99Kqv7zCx7e9z/KhowoKPGltZyBzcmM9"http://img.blog.csdn.net/20141105081542390?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3V1Z2xlMjAxMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="\">
代碼如下:
#include
const int COCKPR = 3;
const int HENPR = 5;
const double CHICKPR = 1/3;
void buyChicken(int money, int chooks);
int main()
{
int money = 100;
int chooks = 100;
buyChicken(money, chooks);
return 0;
}
void buyChicken(int money, int chooks)
{
using namespace std;
int MaxCock = money/COCKPR;
int MaxHen = money/HENPR;
int MaxChick = chooks;
int MinChick = chooks-MaxCock-MaxHen;
int cock,hen,chick;
int count = 0;
for(cock=0; cock<= MaxCock; cock++)
{
for(hen=0; hen<=MaxHen; hen++)
{
for(chick=MinChick; chick<=MaxChick; chick++)
{
if (0 == chick%3 && cock + hen + chick == chooks && COCKPR*cock + HENPR*hen + CHICKPR*chick == money)
cout << "公雞: " << cock << " 母雞: " << hen << " 小雞: " << chick << " 第 " << count << "有結果" <
填數字游戲
代碼:
#include
int main()
{
using namespace std;
int t1,t2,t3,t4,t5;
for (t1=1; t1<=9; t1++)
{
for(t2=0; t2<=9; t2++)
{
for(t3=0; t3<=9; t3++)
{
for(t4=0; t4<=9; t4++)
{
for(t5=0; t5<=9; t5++)
{
if(t5*100000 + t5*10000 + t5*1000 + t5*100 + t5*10 + t5 == t5*t1 + t4*t1*10 + t3*t1*100 + t2*t1*1000 + t1 *t1*10000 )
{
cout << " 算的數值為: " << t1 << " 法的數值為: " << t2 << " 描的數值為: " <
運行結果: