lmarkov

Subset Sums

Dec 14th, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 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 SubsetSums
  8. {
  9.     class SubsetSums
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             long numbersSumS = long.Parse(Console.ReadLine());
  14.             byte numbersCountN = byte.Parse(Console.ReadLine());
  15.  
  16.             long[] numbers = new long[numbersCountN];
  17.  
  18.             for (int i = 0; i < numbersCountN; i++)
  19.             {
  20.                 numbers[i] = long.Parse(Console.ReadLine());
  21.             }
  22.             int maximumLoops = (int)Math.Pow(2, numbersCountN) - 1;
  23.             int counter = 0;
  24.             for (int i = 1; i <= maximumLoops; i++)
  25.             {
  26.                 long currentSum = 0;
  27.                 for (int j = 0; j < numbersCountN; j++)
  28.                 {
  29.                     long bitValue = ((1 << j) & i) >> j;
  30.                     if (bitValue == 1)
  31.                     {
  32.                         currentSum += numbers[j];
  33.                     }
  34.                 }
  35.                 if (currentSum == numbersSumS)
  36.                 {
  37.                     counter++;
  38.                 }
  39.             }
  40.             Console.WriteLine(counter);
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment