0

我已经阅读了其他一些讨论,但不知道如何修复我的程序。随着它的递归,我的索引计数器最终变得太大,并且由于它超出了范围(或者至少我认为这是正确的),因此承诺不起作用。我该如何解决这个问题,以使索引永远不会变得太大?

vector<uint> w;                // vector of weights
vector<bool> include;
uint W;                        // the desired weight
uint index = 0;
uint weight = 0;               // the current weight of subsets
uint total = 0;                // superset total

void sum_of_subsets( uint index,
                     uint weight,
                     uint total,
                     vector<bool> &include,
                     vector<uint> &w,
                     uint W )
{
    if( promising(index, weight, W, w, total) )
    {
        if( weight == W )
        {
            for( uint k = 0; k <= include.size(); k++ )
            {
                if(include.at(k))
                    cout << w.at(k) << " ";
            }
        }
        else
        {
            include.at(index + 1) = 1;
            sum_of_subsets( index + 1, 
                            weight + w.at(index + 1 ), 
                            total - w.at(index + 1),
                            include, w, W ) ;
            include.at(index + 1) = 0;
            sum_of_subsets( index + 1, 
                            weight, 
                            total - w.at(index + 1),
                            include, w, W );
        }
    }
}

bool promising ( uint index, 
                 uint weight, 
                 uint W, 
                 vector<uint> w,
                 uint total )
{
    return ( weight + total >= W )
            && ((weight == W) || (weight + w.at(index+1) <= W));
}
4

0 回答 0