The partial sum problem
时间限制:1000 ms | 内存限制:65535 KB
难度:2
输入
There are multiple test cases.
Each test case contains three lines.The first line is an integer N(1≤N≤20),represents the array contains N integers. The second line contains N integers,the ith integer represents A[i](-10^8≤A[i]≤10^8).The third line contains an integer K(-10^8≤K≤10^8).
输出
If Tom can choose some integers from the array and their them is K,printf ”Of course,I can!”; other printf ”Sorry,I can’t!”.
样例输入
4 1 2 4 7 13 4 1 2 4 7 15
样例输出
Of course,I can! Sorry,I can't!
来源
上传者
描述
One day,Tom’s girlfriend give him an array A which contains N integers and asked him:Can you choose some integers from the N integers and the sum of them is equal to K.
题意:给你n个数,以及一个s,问能不能从这n个数中选出几个数是的它们的和等于s。若可以输出 Of course,I can! 否则输出 Sorry,I can't!
思路:n的范围是20,20个数取或不取那么时间复杂度是2^20,大约是一百万,应该是可以过的。但是坑爹的是非要加上一个剪枝才能过,但我觉得那个剪枝是错的。具体看代码注释
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<map>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define LL long long
const int N=20;
int n,a[N],s,flag;
void dfs(int k,int sum)
{
//那我们就说一说这个剪枝,当总和sum大于s时就直接返回不再搜下去了。
//但题目已经很明确的说了给的数组有负数的情况,可能当前sum的值大于s
//但没有加的数组值中可能存在负数使得他们相等,因此我认为这里的剪枝不合理,后台数据应该是只有只都是正的样例
if(sum>s) return ;//加上这个才能过,否则超时
if(sum==s)
{
flag=1;
return ;
}
if(flag||k==n) return ;//flag为真则说明已经找到答案,直接返回即可,k=n搜到最后一个数,直接返回即可
//对于当前这个数取或不取
dfs(k+1,sum);//不加上这个数
dfs(k+1,sum+a[k]);//加上这个数
}
int main()
{
while(~scanf("%d",&n))
{
flag=0;
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&s);
dfs(0,0);
if(flag) printf("Of course,I can!\n");
else printf("Sorry,I can't!\n");
}
}