/*
问题描述:
W的书包装,n件物品(依此w[i]、P[i])如何选取使得利益最大
思路:
按P[i]/w[i]排序进行选择,直至不能选择
数据结构:类
*/
#include<iostream>
#include<algorithm>
using namespace std;
class Knap {
public:
Knap(int N,float M,float *weight,float *P);
void greedy(float *x);
float MaxPro(float *X);
// int ReturnOder();
private:
int n;
float m,*w,*p;
// int *order;
};
/*int Knap::ReturnOder(){
while()
}*/
float Knap::MaxPro(float *X) {
float MaxProfile=0;
int i=0;
while(X[i]) {
MaxProfile+=X[i]*p[i];
i++;
}
return MaxProfile;
}
Knap::Knap(int N,float M,float *weight,float *P) {
n=N;
m=M;
w=weight;
p=P;
}
void Knap::greedy(float *x) {
for(int i=0; i<n; i++)x[i]=0;
float u=m;
for(int i=0; i<n; i++) {
if(w[i]<u) {
x[i]=1;
u-=w[i];
} else {
x[i]=u/w[i];
break;
}
}
}
int main() {
int M=6,N=3,order[3]= {0,1,2};
float WW[3]= {2,3,4},PP[3]= {1,2,4};
for(int i=0; i<N; i++) {
for(int j=0; j<N-1-i; j++) {
if(PP[j]/WW[j]<PP[j+1]/WW[j+1]) {
swap(PP[j],PP[j+1]);
swap(WW[j],WW[j+1]);
swap(order[j],order[j+1]);
}
}
}
Knap KK(N,M,WW,PP);
float XX[3];
KK.greedy(XX);
cout<<"Max:"<<KK.MaxPro(XX);
cout<<XX[0]<<" "<<XX[1]<<" "<<XX[2];
int i=0;
cout<<"序列:";
while(XX[i]) {
cout<<order[i]<<"->";
i++;
}
return 0;
}
动态规划--背包问题
猜你喜欢
转载自blog.csdn.net/qq_44654974/article/details/106574992
今日推荐
周排行