摘要

题目链接 难度等级 完成状态 完成分数 最后编辑时间 需要注意
砝码称重 2 ★★☆☆☆ 答案正确 100 2015-2-3 22:46:13

题意

n个砝码凑齐总重量m,每个砝码至多用一次,问最少砝码数。

题解

  • 一开始愣了一下还去想贪心,和CodeVS/1099异曲同工,也是双向搜索+哈希/map解决。

代码

2144.cpp代码已折叠
展开折叠内容
显示/移除行号
  1. #include<cstdio>
  2. #include<map>
  3. #include<iostream>
  4. #include<climits>
  5. using namespace std;
  6. map<int,int> ans;
  7. int n,m;
  8. int w[1000]={},Ans=INT_MAX;
  9. void dfs(const int &_index,const int &_weight,const int &_count)
  10. {
  11. if(_index>(n>>1)+1)
  12. return;
  13. if(ans.count(_weight))
  14. ans[_weight]=min(ans[_weight],_count);
  15. else
  16. ans[_weight]=_count;
  17. dfs(_index+1,_weight+w[_index],_count+1);
  18. dfs(_index+1,_weight,_count);
  19. }
  20. void rdfs(const int &_index,const int &_weight,const int &_count)
  21. {
  22. if(_index<(n>>1))
  23. return;
  24. if(ans.count(m-_weight))
  25. Ans=min(ans[m-_weight]+_count,Ans);
  26. rdfs(_index-1,_weight+w[_index],_count+1);
  27. rdfs(_index-1,_weight,_count);
  28. }
  29. int main()
  30. {
  31. cin>>n>>m;
  32. for(int i=1;i<=n;++i)
  33. cin>>w[i];
  34. dfs(1,0,0);
  35. rdfs(n,0,0);
  36. cout<<Ans;
  37. return 0;
  38. }
  39.  

著作权声明[编辑]

关于[编辑]