Tuesday, 11 August 2015

UVa 624 - CD

///     Raihan Ruhin
///     CSE, Jahangirnagar University.
///     Dhaka-Bangladesh.
///     id: raihanruhin (topcoder / codeforces / codechef / hackerrank / uva / uvalive / spoj), 3235 (lightoj)
///     mail: raihanruhin@ (yahoo / gmail / facebook)
///     blog: ruhinraihan.blogspot.com

#include<bits/stdc++.h>
using namespace std;

#define SET(a) memset(a,-1,sizeof(a))
#define CLR(a) memset(a,0,sizeof(a))
#define PI acos(-1.0)

#define MOD 1000000007
#define MX 100010

int n, m, track[22], sum, ans;

int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);
    int tc, kk=1;
    string s;
    char ch;
    while(cin>>n)
    {
        cin>>m;
        for(int i=0;i<m;i++) cin>>track[i];

        int lmt=1<<m, mx=0;
        for(int i=1;i<lmt;i++)
        {
            sum=0;
            for(int j=0;j<m;j++)
                if((i & (1<<j)))
                    sum+=track[j];
            if(sum<=n && sum>mx)
                mx=sum, ans=i;
        }
        for(int j=0;j<m;j++)
            if(ans & (1<<j))
                cout<<track[j]<<" ";
        cout<< "sum:"<< mx <<"\n";
    }
return 0;
}

1 comment:

  1. A question I am new to competitive programming, I would like to know if this exercise solved it with the Backtracking algorithm thanks

    ReplyDelete