dfs,搜索,林大超市买水果-搜索
Problem:1519
Time Limit:1000ms
Memory Limit:65535K
Description
林大的超市有N种水果,18级的新生小王同学兜里有M元钱,想买K种水果,但他想刚刚把M元钱花完,有这个可能吗?
Input
第一行输入M,N,K含义如上;(1<=M<=1e8,1<=n<=30,1<=k<=8) 接下来是每种水果的价格;
Output
如果可以的话,输出Yes; 否则输出No;
Sample Input
20 5 3 1 2 3 15 6
Sample Output
Yes
解析:
这明显是一个不选的问题,提到这里,可能就会想到用二进制枚举或dfs搜索
但到底用哪个更好呢:
二进制枚举:时间复杂度为O(2^30),而且很难做剪枝;
dfs:如果没有k<=8的限制,时间复杂度与二进制枚举一样,但题目说k<=8,所以我们在dfs记录已经选了多少个数字num,num>=k的时候就跳出。这样,在dfs的过程中就已经自动的进行了剪枝,将很多不符合题目要求的情况打断,所有时间复杂度是远远到不了O(2^30)
因此我们选择dfs进行搜索
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
using namespace std;
int n, m, k;
int arr[35];
int dfs(int p, int num,int sum) {
if (num == k&&m==sum)
return 1;
if (num == k)
return 0;
for (int i = p + 1; i <= n; i++) {
int a=dfs(i, num + 1, sum + arr[i]);
if (a)
return 1;
}
return 0;
}
int main() {
scanf("%d%d%d", &m, &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
}
if (dfs(0,0,0)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
using namespace std;
typedef long long LL;
int n, m, k;
int arr[35];
int dfs(int p, int num, LL sum) {
if (num == k && m == sum)
return 1;
if (num == k||p>n||m<sum)
return 0;
int a = dfs(p + 1, num + 1, sum + arr[p]);
int b = dfs(p + 1, num, sum );
if (a || b)
return 1;
return 0;
}
int main() {
scanf("%d%d%d", &m, &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
}
if (dfs(1,0,0)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}