April 2019

Zed's Dead Baby

Solution

Read about bitmasks here : https://codeforces.com/blog/entry/18169


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() 
{
    
    int t;
    cin>>t;
    while(t-->0)
    {
        int m,n;
        string ans ="NO\n";
        cin>>m>>n;
        int keys[m];
        for(int i=0;i<m;i++)
            cin>>keys[i];
        for(int i=0;i<(1<<m);i++) // bitmask
        {
            int sum=0,c=0; 
            for(int j=0;j<m;j++)
            {
                if((i&(1<<j))) // check if bit is set
                { 
                  sum+=keys[j];
                 
                  c++;
                }
                    
            }
            
            if(c>1)
                sum-=(c-1)*2;// since 2 nodes are used to attack the trees, they won't be nodes anymore xD
            //so every time we add a new tree we need to subtract 2
           
            
            if(sum==n)
            {
                
                ans ="YES\n";
                break;
            }
            
        }
        cout<<ans;
        
    }
    return 0;
}

Time Complexity: $O(2^m * m)$ per testcase

Space Complexity: $O(m)$