贪心算法算法设计
内容:
- 0/1背包
- 背包问题
- 任务分配
0/1背包
/思想是不难 但主要是处理好double()这部分的位置 /*#include<iostream> using namespace std; int w[10]={42,30,10}; int v[10]={170,120,50}; int c=50; void sort(int w[],int v[],int c) { for(int i=0;i<3;i++) for(int j=i+1;j<3;j++) if( double( v[j] )/w[j]> double (v[i])/w[i]) { int temp=v[i]; v[i]=v[j]; v[j]=temp; int pos=w[i]; w[i]=w[j]; w[j]=pos; } cout<<"sort"<<endl; for( i=0;i<3;i++) cout<<v[i]<<" "<<w[i]<<endl; } int knap(int w[],int v[],int c) { int maxvalue=0; for(int i=0;w[i]<=c;i++) { maxvalue+=v[i]; c=c-w[i]; } return maxvalue; } int main() { sort(w,v,c); cout<<knap(w,v,c)<<endl; return 0; }
注意:0/1背包是全部转入的问题,背包问题是可以部分装入的
背包问题:
#include<iostream> using namespace std; int w[10]={20,30,10}; int v[10]={60,120,50}; int c=50; void sort(int w[],int v[],int c) { for(int i=0;i<3;i++) for(int j=i+1;j<3;j++) if( double( v[j] )/w[j]> double (v[i])/w[i]) { int temp=v[i]; v[i]=v[j]; v[j]=temp; int pos=w[i]; w[i]=w[j]; w[j]=pos; } cout<<"sort"<<endl; for( i=0;i<3;i++) cout<<v[i]<<" "<<w[i]<<endl; } int knap(int w[],int v[],int c) { int maxvalue=0; for(int i=0;w[i]<=c;i++) { maxvalue+=v[i]; c=c-w[i]; } return maxvalue+double(c)*v[i]/w[i];//计算上不能装的部分装 } int main() { sort(w,v,c); cout<<knap(w,v,c)<<endl; return 0; }
任务分配:
#include<iostream> using namespace std; int s[20]={1,3,0,5,3,5,6,8,8,2,12}; int f[20]={4,5,6,7,8,9,10,11,12,13,14}; int count=0; void sort(int s[],int f[],int n) { for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if( f[j]<f[i]) { int temp=f[i]; f[i]=f[j]; f[j]=temp; int pos=s[i]; s[i]=s[j]; s[j]=pos; } cout<<"sort"<<endl; for( i=0;i<n;i++) cout<<f[i]<<" "<<s[i]<<endl; } void divice(int s[],int f[],int v[] ) { int start=0; for(int i=0;i<11;i++) { if(s[i]>f[start]) { v[count++]=s[i]; start=i; } } } int main() { int v[100]={0}; sort(s,f,11); divice(s,f,v); cout<<endl; for(int i=count-1;i>=0;i--) cout<<v[i]<<" "; return 0; }
总结:
我们不难发现0/1背包的核心部分是先进行排序,排序按照所谓的单位价值最大进行求解