Advertisement
sashomaga

Subset Sums

Dec 26th, 2012
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2. //You are given a list of N numbers. Write a program that counts all non-empty subsets from this list, which have sum of their elements exactly S.
  3. //Example: if you have a list with 4 elements: { 1, 2, 3, 4 } and you are searching the number of non-empty subsets which sum is 4, the answer will
  4. //be 2. The subsets are: { 1, 3 } and { 4 }.
  5. //Input
  6. //The input data is being read from the console.
  7. //On the first input line there will be the number S.
  8. //On the second line you must read the number N.
  9. //On each of the following N lines there will be one integer number written – all the numbers from the list.
  10. //The input data will always be valid and in the format described. There is no need to check it explicitly.
  11. //Output
  12. //The output must be printed on the console.
  13. //On the only output line you must print the number of the non-empty subsets, which have sum of all its elements exactly S.
  14.  
  15.  
  16. class Program
  17. {
  18.     static void Main()
  19.     {
  20.         long s = long.Parse(Console.ReadLine());
  21.         int n = int.Parse(Console.ReadLine());
  22.         long[] num = new long[n];
  23.  
  24.         for (int i = 0; i < n; i++)
  25.         {
  26.             num[i] = long.Parse(Console.ReadLine());          
  27.         }
  28.  
  29.         long sum = 0;
  30.         int answer = 0;
  31.         for (int i = 1; i < Math.Pow(2, n); i++)
  32.         {
  33.             for (int j = 0; j < num.Length; j++)
  34.             {
  35.                 if ((i >> j & 1) == 1)
  36.                 {
  37.                     sum += num[j];
  38.                 }
  39.             }
  40.             if (sum == s)
  41.             {
  42.                 answer++;
  43.             }
  44.             sum=0;
  45.         }
  46.         Console.WriteLine(answer);
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement