数组中的组合问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_33442459/article/details/77981543



题目描述:

给出n(0<n<=100000)个数,其中任意两个数a,b(0<=a,b<10^9),必然会出现a整除b或者b整除a,给出m(0<m<=100000)个查询,每个查询给出一个p(0<p<10^9),问n个数里是否可以组合出一个子集,和为p

输入:

第一行输入n,m

第二行输入n个数,范围为[0,10^9]

随后m行每行输入一个p


输出:

输出存在满足要求的子集的查询个数


样例输入

5 2

4 2 2 4 4

8

9


样例输出

1


#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <list>
#include <map>
using namespace std;

int main()
{
	unsigned n,m,num,temp;
	cin>>n>>m;
	map<unsigned,unsigned>imap;
	unsigned min = 10e9 , count = 0;
	map<unsigned, unsigned>::iterator p;
	for (unsigned i = 0 ; i < n ; ++ i)
	{
		cin>>temp;
		if (imap.find(temp) != imap.end())
		{
			++imap.find(temp)->second;
		}else
		{
			imap.insert(pair<unsigned,unsigned>(temp,1));
		}
		min = min < temp ? min : temp;
	}
	while (m>0)
	{
		cin>>num;
		if (num % min == 0)
		{
			for(map<unsigned, unsigned>::reverse_iterator  iter = imap.rbegin();iter!=imap.rend();++ iter)
			{
				if (num >= iter->first * iter->second)
				{
					num -= iter->first * iter->second;
				}else
				{
					num -= (num / iter->first)*iter->first;
				}
			}
			if (num == 0)
			{
				++count;
			}
		}
		--m;
	}
	cout<<count;
	system("pause");
	return 0;}







猜你喜欢

转载自blog.csdn.net/sinat_33442459/article/details/77981543