C++~回溯+貪心法解決01背包問題
阿新 • • 發佈:2018-01-01
void clu 參考 play pan col pac ace 直接
如果是寫作業找到了我這裏,希望不要直接copy~僅供參考~可能有錯誤的,自己寫幫助很大^0^
#include<iostream> #include<string.h> #include<stdlib.h> using namespace std; struct item{ double weight,value; int index; }; struct item items[101]; int x[101]; int res[101]; int n; double c; double max_value; bool isOk(int t){int i,j; double max_c=c,max_v=0; for(i=0;i<=t;i++){ if(x[i]==1){ max_v+= items[i].value; max_c-= items[i].weight; } if(max_c < 0){ return false; } } for(;i<=n-1;i++){ if(max_c >= items[i].weight){ max_v+= items[i].value; max_c-= items[i].weight; } else { max_v=max_v+( max_c*(items[i].value/items[i].weight) ); max_c=0; break; } } if(max_v < max_value) return false; return true; } void backtrack(int t){ int j;if(t>=n){ double cur=0; for(j=0;j<n;j++){ if(x[j]==1) cur+=items[j].value; } if(cur>max_value){ max_value = cur; for(j=0;j<n;j++){ res[j]=x[j]; } } return; } for(int i=1;i>=0;i--){ x[t]=i; if(isOk(t)){ backtrack(t+1); } } } void swap(int i,int j){ struct item temp; temp = items[i]; items[i] = items[j]; items[j] = temp; } void sort(int left,int right){ if(left > right) return; int i,j; struct item temp; i=left; j=right; temp = items[left]; while(i!=j){ while(items[j].value/items[j].weight <= temp.value/temp.weight && i<j){ j--; } while(items[i].value/items[i].weight >= temp.value/temp.weight && i<j){ i++; } if(i<j){ swap(i,j); } } items[left] = items[i]; items[i] = temp; sort(left,i-1); sort(i+1,right); } void displayRes(){ for(int i=0;i<=n-1;i++){ for(int j=0;j<=n-1;j++){ if(items[j].index == i){ cout<<res[j]<<" "; break; } } } cout<<endl; } int main(){ cin>>c>>n; max_value=0; for(int i=0;i<n;i++){ cin>>items[i].weight>>items[i].value; items[i].index=i; x[i]=0; res[i]=0; } sort(0,n-1); backtrack(0); displayRes(); cout<<max_value<<endl; }
C++~回溯+貪心法解決01背包問題