NYOJThe partial sum problem927

来源:互联网 发布:阿里云公网宽带 编辑:程序博客网 时间:2024/04/27 21:44

The partial sum problem
时间限制:1000 ms | 内存限制:65535 KB
难度:2

描述
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 Ai.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!”.
样例输入

41 2 4 71341 2 4 715

样例输出

Of course,I can!Sorry,I can't!

这题和部分和问题一样,只是输出简单了些,如果想看多种做法,可以看看下篇部分和的介绍

#include<stdio.h>#include<string.h>int a[25],b[25];int n,k,flag;void fun(int pos,int sum){    if(flag)//大大滴加快了效率    {        return;    }    if(sum>k)    {        return;    }    if(sum==k)    {        flag=1;        printf("Of course,I can!\n");                       return;    }    for(int i=pos;i<n;i++)    {        sum+=a[i];        b[i]=1;        fun(i+1,sum);        sum-=a[i];        b[i]=0;    }}int main(){    while(scanf("%d",&n)!=EOF)    {        memset(b,0,sizeof(b));        for(int i=0;i<n;i++)        {            scanf("%d ",&a[i]);        }           scanf("%d",&k);        flag=0;        fun(0,0);        if(!flag)        {            printf("Sorry,I can't!\n");        }     }     return 0; } 
0 0