The partial sum problem(DFS+减枝)

描述 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. 

输入

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!


题目大意:多组数据测试,每组给一个N和N个数字,一个K。判断是否有给出的数字相加等于K,若有则输出Of course,I can!,若无则输出Sorry,I can't! ,时间限制:1000ms。

思路:读完题思路还是很清晰的,可以用递归解决但会超时,在纠结了很久后选择放弃了递归使用DFS,直接DFS与递归没有什么区别,还是超时,所以需要进行减枝(实在是我的弱项啊)。
#include<iostream>
#include<stdio.h>
using namespace std;
int n,s,a[21],flag,i,j;
void dfs(int i, int sum)//传入位置与当前和s
{
      if(i==n+1) 
      {
	     return ;
      }
      if(sum>s) 
      {
	     return ;//减枝
      }
      if(sum==s) 
      {
          flag=1;
          return ;
      }
      dfs(i+1,sum);
      dfs(i+1,sum+a[i]);//对于第i+1个数取与不取
} 
int main() 
{
    while (scanf("%d",&n)!=EOF) 
    {
       flag=0;
       for(i=0;i<n;i++)
       {
	      scanf("%d",&a[i]);
	   }
       scanf("%d",&s);
       dfs(0,0);
       if(flag!=0) 
	   {
          printf("Of course,I can!\n");
           }
	   else
	   {
          printf("Sorry,I can't!\n");
       }
    }
    return 0;
}//感觉DFS减枝与我之前写的递归没什么区别,但就是要超时,作为一个小白我暂时也很迷


阅读更多
文章标签: DFS  减枝
个人分类: 算法训练
上一篇3D dungeon(BFS)
下一篇Card Trick(模拟)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭