初学ACM,问下口袋问题的算法(杭电2602)
为何不能把骨头的价值除以体积的数组排序(如价值5,体积1,价值除以体积就是5,放在double数组里,简称value),然后让value值高优先放入袋子中计算呢?(WRO...
为何不能把骨头的价值除以体积的数组排序(如价值5,体积1,价值除以体积就是5,放在double数组里,简称value),然后让value值高优先放入袋子中计算呢?(WRONG ANSWER了)
袋子问题的算法已经看过一下了,还没看明白,想先请教下这种方法错哪了,最好能举出特殊例子。感激不尽!(本人大一,请不要讲的那么深奥)
以下为代码:
#include<iostream>#include<string>#include<algorithm>#include<vector>#include<sstream>#include<cstring>#include<math.h>#include<stdio.h>#include<map>#include<set>using namespace std;
struct node{ int w; int v; double value;
bool operator <(const node& b) const { if(this->value != b.value) return (this->value)<(b.value); else return this->v>b.v; }};
int main(){ int T; scanf("%d",&T); while(T--) { int N,V; cin>>N>>V; node *nodes=new node[N];
for(int i=0;i<N;++i) { int temp; scanf("%d",&temp); nodes[i].w=temp; } for(int i=0;i<N;++i) { int temp; scanf("%d",&temp); nodes[i].v=temp; } double tempa,tempb; for(int i=0;i<N;++i) { tempa=(double)nodes[i].w; tempb=(double)nodes[i].v; if(tempb!=0) nodes[i].value=(tempa/tempb); else nodes[i].value=100000; }
sort(nodes,&nodes[N]); __int32 sum=0; for(int i=N-1;i>=0;--i) { if(nodes[i].v<=V) { sum+=nodes[i].w; V-=nodes[i].v; } } cout<<sum<<endl; delete[] nodes; } return 0;} 展开
袋子问题的算法已经看过一下了,还没看明白,想先请教下这种方法错哪了,最好能举出特殊例子。感激不尽!(本人大一,请不要讲的那么深奥)
以下为代码:
#include<iostream>#include<string>#include<algorithm>#include<vector>#include<sstream>#include<cstring>#include<math.h>#include<stdio.h>#include<map>#include<set>using namespace std;
struct node{ int w; int v; double value;
bool operator <(const node& b) const { if(this->value != b.value) return (this->value)<(b.value); else return this->v>b.v; }};
int main(){ int T; scanf("%d",&T); while(T--) { int N,V; cin>>N>>V; node *nodes=new node[N];
for(int i=0;i<N;++i) { int temp; scanf("%d",&temp); nodes[i].w=temp; } for(int i=0;i<N;++i) { int temp; scanf("%d",&temp); nodes[i].v=temp; } double tempa,tempb; for(int i=0;i<N;++i) { tempa=(double)nodes[i].w; tempb=(double)nodes[i].v; if(tempb!=0) nodes[i].value=(tempa/tempb); else nodes[i].value=100000; }
sort(nodes,&nodes[N]); __int32 sum=0; for(int i=N-1;i>=0;--i) { if(nodes[i].v<=V) { sum+=nodes[i].w; V-=nodes[i].v; } } cout<<sum<<endl; delete[] nodes; } return 0;} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询