主题:买票问题
有2n个人排队购一件价为0.5元的商品。其中一半人拿了一张1元票,另一半人拿了一张0.5元的票。而售货员一开始就没有准备零钱,如果要使她在售货中不发生找钱困难,问这2n个人应该如何排队?找出所有排队的方案。
我用回溯做的,本着"1块钱不能多与5毛钱"的原则,设5毛钱是-1,一块是1,累加这些值,如果值大于0就回溯.
my code:
/////////////////////////
#include <iostream>
using namespace std;
int tot;
void stanline (int a, int b, int v, char queue[], int i)
{
if (v > 0)
return;
if (a == 0 && b == 0) {
tot++;
for (int j = 0; j < i; ++j)
cout << (queue[j] != -1) << ' ';
cout << endl;
}
if (a > 0) {
queue[i] = -1;
stanline (a - 1, b, v - 1, queue, i + 1);
}
if (b > 0) {
queue[i] = 1;
stanline (a, b - 1, v + 1, queue, i + 1);
}
}
int main ()
{
char queue[10];
stanline (5, 5, 0, queue, 0);
cout << tot << endl;
system ("pause");
return 0;
}
n=5的时候tot=42不知道对不对.
我用回溯做的,本着"1块钱不能多与5毛钱"的原则,设5毛钱是-1,一块是1,累加这些值,如果值大于0就回溯.
my code:
/////////////////////////
#include <iostream>
using namespace std;
int tot;
void stanline (int a, int b, int v, char queue[], int i)
{
if (v > 0)
return;
if (a == 0 && b == 0) {
tot++;
for (int j = 0; j < i; ++j)
cout << (queue[j] != -1) << ' ';
cout << endl;
}
if (a > 0) {
queue[i] = -1;
stanline (a - 1, b, v - 1, queue, i + 1);
}
if (b > 0) {
queue[i] = 1;
stanline (a, b - 1, v + 1, queue, i + 1);
}
}
int main ()
{
char queue[10];
stanline (5, 5, 0, queue, 0);
cout << tot << endl;
system ("pause");
return 0;
}
n=5的时候tot=42不知道对不对.