回 帖 发 新 帖 刷新版面

主题:买票问题

有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不知道对不对.

回复列表 (共5个回复)

沙发

用堆栈可以吗?拿0.5元的进栈,指针递增,当出现一个1元的就消去一个,指针递减

板凳

不错啊

3 楼

判断 0.5元的数目 > 1 元的数目

4 楼

问一个问题,为什么我建一个console application后把上面的代码copy上后再运行,说iostream里有一句static ios_base::Init _Ios_init;报错是:INTERNAL COMPILER ERROR.大哥可以告诉我吗?

5 楼

google后得出结论,是你的vc路径设置有问题.

我来回复

您尚未登录,请登录后再回复。点此登录或注册