BFS (图)——Codeforces 788 C. The Great Mixing

来源:互联网 发布:社交网络营销策划方案 编辑:程序博客网 时间:2024/05/21 22:26

题目:
http://codeforces.com/contest/788/problem/C

           **The Great Mixing**

Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration . Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration . The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.

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.

input

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.

output

Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration , or -1 if it is impossible.

Example

>Input>400 4>100 300 450 500>Output>2>Input>50 2>100 25>Output>3

AC代码:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <string>#include <queue>#include <vector>#define  INF  0x3f3f3f3f#define  maxi 2000 + 10#define  maxj 1000 + 10using namespace std;vector <int> v;int n, k;int dp[maxi];int in[maxj];queue <int > Q;void bfs(){     for (int i = 0; i <= 1000; i++)     {         if (in[i])            {                v.push_back(n-i);                int x = n - i + 1000;                dp[x] = 1;                if (x == 1000) break;                Q.push(x);            }     }     while(Q.size())     {         int t = Q.front(); Q.pop();         for (int i = 0; i < v.size(); i++)         {             int x = t + v[i];             if (x >= 0 && x <= 2000 && dp[x] > dp[t] + 1)             {                 dp[x] = dp[t] + 1;                 Q.push(x);             }         }     }}int main(){    memset(in,0,sizeof(in));    memset(dp,INF,sizeof(dp));   cin >> n >> k;   int b;   for (int i = 1; i <= k; i++)     {         scanf("%d",&b);         in[b] = 1;     }   bfs();   if (dp[1000] >= INF)  cout << "-1" << endl;    else cout << dp[1000] <<endl;   return 0;}

解析:

1.bfs
2.图
3.状态转换
4.S(ki * (n - a[i]) =0) ki 和最小(推导)

0 0
原创粉丝点击