psotirov

Subset Sums

Dec 10th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.03 KB | None | 0 0
  1. using System;
  2.  
  3. class SubsetSums
  4. {
  5.     static void Main()
  6.     {
  7.         long S = long.Parse(Console.ReadLine()); // the sum to look
  8.         int N = int.Parse(Console.ReadLine()); // quantity of numbers
  9.         int count = 0; // Subset Sums counter
  10.  
  11.         long[] numbers = new long[N];
  12.         for (int i = 0; i < N; i++) // Loop to enter  numbers
  13.         {
  14.             numbers[i] = long.Parse(Console.ReadLine()); // reads from the console
  15.         }
  16.  
  17.         int combinations = (1 << N)-1; // number of different combinations of the numbers is 2^N-1 (excluding 0)
  18.         for (int i = 1; i <= combinations; i++) // iterates through each combination
  19.         {
  20.             long Sum = 0;
  21.             for (int j = 0; j < N; j++) // checks each bit in i-th combination
  22.                 if (((i >> j) & 1) == 1) Sum += numbers[j]; // and if bit is set includes corresponding number into the sum
  23.             if (Sum == S) count++; // each sum equal to S increases the counter
  24.         }
  25.  
  26.         Console.WriteLine(count);
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment