![](https://i-blog.csdnimg.cn/blog_migrate/1d1aa3bee72aa8d518dd568a0f988128.png)
![](https://i-blog.csdnimg.cn/blog_migrate/730827dc694c784c6adf7e883871d100.png)
Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.
Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration . Assume that the friends have unlimited amount of each Coke type.
The first line contains two integers n, k (0 ≤ n ≤ 1000, 1 ≤ k ≤ 106) — carbon dioxide concentration the friends want and the number of Coke types.
The second line contains k integers a1, a2, ..., ak (0 ≤ ai ≤ 1000) — carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.
Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration , or -1 if it is impossible.
400 4 100 300 450 500
2
50 2 100 25
3
In the first sample case, we can achieve concentration using one liter of Coke of types
and
:
.
In the second case, we can achieve concentration using two liters of
type and one liter of
type:
题意:就是先给你两个数分别是n,k然后再输入k个数,问你在这k个数里最少取多少个数使得他们的平均数为n;
分析:
思路:先按上图进行分析,不难得出每个点的贡献值为(si-n)最后贡献值为0即可。求最小,先将数据进行处理,再进行bfs(这样就可以将所有的组合表示出来,当和为0时,跳出)
代码:
#include <bits/stdc++.h>
using namespace std;
bool visit[1001];
int ans[2002];//记录到达下标当前状态下的最小值
int n,k;
int to;
int i;
vector<int>vec;
void bfs()
{
for(i=0;i<2002;i++) ans[i]=-1;//赋初值
queue<int>q;
q.push(0);
ans[0]=0;//初值
while(!q.empty()){
int v=q.front();q.pop();
for(i=0;i<vec.size();i++){
to=v+vec[i];//当前贡献值
if(to==0){
ans[to]=ans[v]+1;
cout<<ans[to];
return ;
}
if(to>0&&to<2002&&ans[to]==-1){//当出现第一次时肯定为最小
ans[to]=ans[v]+1;//相当于保存bfs的层数
q.push(to);//满足条件进行push()
}
}
}
cout<<-1;
}
int main()
{
for(i=0;i<1001;i++)
visit[i]=false;
scanf("%d%d",&n,&k);
while(k--){
int x;scanf("%d",&x);
if(!visit[x]){//保存每个数的贡献值,因为某些数需要重复出现,但是保存一次就够了
vec.push_back(x-n);
visit[x]=true;
}
}
bfs();
}