将背包装满,要求时间复杂度最小 给定参数,背包容量S=100,N个物品,重量分别为1,55,2,44,3,5,3,56,7,3,5...
<pre name="code" class="cpp">class Test
{
public:
//将背包装满,要求时间复杂度最小 给定参数,背包容量S=100,N个物品,重量分别为1,55,2,44,3,5,3,56,7,3,5...
vector<int> ve;
void fill_bag(int S, int object_weight[], int len)
{
//一参是数组,二参数组元素数量,三参每个元素的字节数,四参数是函数
qsort(object_weight,len,sizeof(int),compare);
for(int i=len-1; i>=0; i--)
{
int c = S;
int j = i;
while(j>=0 && c>0)
{
j = bi_search(object_weight, j, c);
if(j==-1)
break;
ve.push_back(object_weight[j]);
if(object_weight[j]==c)
{
//ve.push_back(object_weight[j]);
for(int k=0; k<ve.size(); k++)
cout<<ve[k]<<" ";
return;
}
c = c-object_weight[j];
}
ve.clear();
}
}
};
int compare(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
//二分查找离元素(可以等于)
int bi_search(int num[10], int len, int target)
{
int begin = 0;
int end = len-1;
while(begin<end)
{
int mid = (begin+end)/2;
//最近的一个
if(num[mid]==target)
return mid;
else if(num[mid]>target)
end = mid-1;
else
begin = mid+1;
}
cout<<"begin:"<<begin<<"end:"<<end<<endl;
if(begin==end && begin==0)
return -1;
return end;
}
void main1()
{
int num[10]={11,35,65,25,79,54,34,66,92,30};
qsort(num,10,sizeof(int),compare);
for(int i=0;i<10;i++)
cout<<num[i]<<" ";
cout<<endl;
int index = bi_search(num, 10, 36);
cout<<index<<endl;
}
int main()
{
//int num[10]={11,35,65,25,79,54,34,66,92,30};
int num[10]={11,25,30,34,35,54,65,66,79,92};
Test t;
t.fill_bag(100, num, 10);
return 0;
}