-2
#include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;

int help(int i,int money,int denomination[]){
    int sum=0;
    int j=0;
    while(i>0){
        if(i&1) sum+=denomination[j];
        i=i>>1;
        j+=1;
    }
    return sum==money?1:0;
}

int ans(int numOfNotes,int money,int denomination[]){
    for(int i=0;i<(1<<numOfNotes);i++){
        if(help(i,money,denomination)){
            return 1;
        }
    }
    return 0;
}  

int main() {
    int testCases,numOfNotes,money;
    cin>>testCases;
    while(testCases>0){
        cin>>numOfNotes>>money;
        int denomination[numOfNotes];
        int i=0;
        while(numOfNotes){
            cin>>denomination[i];
            i++;
            numOfNotes--;
        }
        testCases--;
        ans(numOfNotes,money,denomination)==1?cout<<"Yes"<<endl:cout<<"No"<<endl;
    }
    return 0;
}

If there exists a subset of array denomination such that it amounts to money, program should show "Yes", else "No".

But for the following simple input

1
3 3
1
1
1

output is coming out to be

No

whereas it should be

Yes

According to me, the for and while loops are not working in the ans and help functions. Is there any other bug in the program?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455

1 Answers1

2

You're modifying numOfNotes in the inner while loop in main, which means its value is 0 when later passed to ans. The loops in the functions are working, you're just giving them other limits than you expected.

You can easily solve issues like this yourself by stepping through your program in a debugger and inspecting variable values and control flow along the way. This is a vital programming skill. See also How to debug small programs by Eric Lippert.


Unrelated to the problem at hand, but please also see these SO questions about what's wrong with including bits/stdc++.h and declaring using namespace std;.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • yeah, like he says, you named a variable i in the function declaration but that does not mean that because you have a variable named i elsewhere it will be used – Mixone May 26 '18 at 12:17