C ++貪欲アルゴリズム分キャンディ

いくつかの子供たちといくつかのお菓子は、それぞれの子は、係数g、各キャンディSの大きさ、必要があると知られている
の使用を必要とする菓子満たす子供を表すお菓子S> =子需要係数gの大きさは、キャンディ、子供の最大数を満たすために?
(一つだけキャンディと子が成立)
、例えば:デマンド因子群G = [5,10,2,9,15,9];配列s = [6,1,20,3,8]の菓子サイズ。 3人の子供を満たすためにアップ。

#include<vector>
#include<algorithm>
class Solution
{
public:
 Solution(){}
 ~Solution(){}
 int findContentChildren(std::vector<int>& g, std::vector<int>& s)
 {
  std::sort(g.begin(), g.end());
  std::sort(s.begin(), s. end());
  unsigned int child = 0;
  unsigned int cookie = 0;
  while (child<g.size() && cookie<s.size())
  {
   if (g[child] <= s[cookie])
   {
    child++;
   }
   cookie++;
  }
  return child;
 }
};
int main()
{
 Solution solve;
 std::vector<int> g;
 std::vector<int> s;
 g.push_back(5);
 g.push_back(10);
 g.push_back(2);
 g.push_back(9);
 g.push_back(15);
 g.push_back(9);
 s.push_back(6);
 s.push_back(1);
 s.push_back(20);
 s.push_back(3);
 s.push_back(8);
 printf("%d\n",solve.findContentChildren(g,s));
 return 0;
}

結果:
3

公開された31元の記事 ウォンの賞賛1 ビュー680

おすすめ

転載: blog.csdn.net/weixin_44208324/article/details/104559299