Problem Description
There is a mountain near yifenfei’s hometown. On the mountain lived a big monster. As a hero in hometown, yifenfei wants to kill it.
Now we know yifenfei have n spells, and the monster have m HP, when HP <= 0 meaning monster be killed. Yifenfei’s spells have different effect if used in different time. now tell you each spells’s effects , expressed (A ,M). A show the spell can cost A HP to monster in the common time. M show that when the monster’s HP <= M, using this spell can get double effect.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m (2<n<10, 1<m<10^7), express how many spells yifenfei has.
Next n line , each line express one spell. (Ai, Mi).(0<Ai,Mi<=m).
Output
For each test case output one integer that how many spells yifenfei should use at least. If yifenfei can not kill the monster output -1.
Sample Input
3 100
10 20
45 89
5 40
3 100
10 20
45 90
5 40
3 100
10 20
45 84
5 40
Sample Output
3
2
-1
此题不难,非常常规的dfs习题。每一次有不同的咒语选择,所以咒语的序号就构成了搜索树。并且每一次都可以选择n种咒语,感觉就是全排列衍伸而来的一道题,只不过全排列中是将1–n的数作为排列对象,这一题是将咒语作为排列对象!
代码:
#include<iostream>
using namespace std;
const int INF = 100;
const int maxn = 15;
int n, M;
int a[maxn];
int m[maxn];
int tag[maxn];
int min_res = INF;
void dfs(int k, int hp) //hp表示怪兽此时的血量
{
if(hp <= 0)
{
if(k < min_res)
min_res = k;
return ;
}
for(int i = 1;i <= n;i++) //每一次咒语的选择都是n种
{
if(tag[i] != 1) //如果咒语没有用过
{
tag[i] = 1;
if(hp <= m[i])
dfs(k + 1, hp - a[i] * 2);
else
dfs(k + 1, hp - a[i]);
tag[i] = 0;
}
}
}
void Clear()
{
for(int i = 1;i <= n;i++)
{
tag[i] = 0;
}
}
int main()
{
while(scanf("%d%d", &n, &M) != EOF)
{
Clear();
min_res = INF;
for(int i = 1;i <= n;i++)
{
cin >> a[i] >> m[i];
}
dfs(0, M);
if(min_res == INF)
cout << "-1" << endl;
else
cout << min_res << endl;
}
return 0;
}