archangelmihail

SubsetSum2

Dec 5th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace SubsetSum2
  8. {
  9.     class SubsetSum2
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             checked
  14.             {
  15.             long sum = long.Parse(Console.ReadLine());
  16.             int n = int.Parse(Console.ReadLine());
  17.             long[] numbers = new long[n];
  18.             // initialization
  19.             for (int i = 0; i < n; i++)
  20.             {
  21.                 numbers[i] = long.Parse(Console.ReadLine());
  22.             }
  23.            
  24.             long combinations = (long)Math.Pow(2, n) - 1;  // how  many combinations we have
  25.             long sumCounter = 0;
  26.  
  27.             //solution
  28.             for (int i = 1; i <= combinations; i++)
  29.             {
  30.                
  31.                 long tempSum = 0;
  32.  
  33.                 for (int j = 0; j < n; j++)
  34.                 {
  35.                     int mask = 1 << j;
  36.                     int iAndMask = mask & i;
  37.                     int bit = iAndMask >> j;
  38.                     /*  bit = (i >> j & 1); */
  39.                     if (bit == 1)
  40.                     {
  41.                         tempSum += numbers[j];
  42.                     }
  43.                 }
  44.                 if (tempSum == sum)
  45.                 {
  46.                     sumCounter++;
  47.                 }
  48.             }
  49.             Console.WriteLine(sumCounter);
  50.             }
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment