No. of subsets whose gcd is 1


                                         

                           Subtraction Game 2 

                                     https://www.codechef.com/problems/AMSGAME2


                       It is only a branch and bound type of recursion.

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. long long int n,i;
  4. long long int a[1000];
  5. long long int dp[70][50010];
  6. long long int go(long long int cur_indx,long long int cur_gcd)
  7. {
  8. if(cur_indx>=n && cur_gcd==1)
  9. return 1;
  10. else if(cur_indx>=n && cur_gcd!=1)
  11. return 0;
  12. if(dp[cur_indx][cur_gcd]!=-1)
  13. return dp[cur_indx][cur_gcd];
  14. else
  15. {
  16. long long int result=0;
  17. result=go(cur_indx+1,cur_gcd); /// without taking a[i];
  18. result+=go(cur_indx+1,__gcd(cur_gcd,a[cur_indx])); /// with taking a[i];

  19. dp[cur_indx][cur_gcd]=result;
  20. return result;
  21. }
  22. }
  23. int main()
  24. {
  25. int t;
  26. cin>>t;
  27. while(t--)
  28. {
  29. // memset(dp,-1,sizeof(dp));
  30. for(int i=0;i<70;i++) for(int j=0;j<10005;j++) dp[i][j]=-1;
  31. cin>>n;

  32. for(i=0;i<n;i++)
  33. cin>>a[i];

  34. cout<<go(0,0)<<endl;
  35. }
  36. return 0;
  37. }

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.