Advertisement
ScorpS

Subset Sum With K Elements

Jan 7th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. //* Write a program that reads three integer numbers N, K and S and an array
  2. //of N elements from the console. Find in the array a subset of K elements that
  3. //have sum S or indicate about its absence.
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7.  
  8. class SubsetSumWithKElements
  9. {
  10.     static void Main()
  11.     {
  12.         int n = int.Parse(Console.ReadLine());
  13.         int countOfElements = int.Parse(Console.ReadLine());
  14.         int sum = int.Parse(Console.ReadLine());
  15.         int[] array = new int[n];
  16.         List<int> subset = new List<int>();
  17.         int max = (2 << array.Length - 1) - 1;
  18.         int currentSum = 0;
  19.         int answer = 0;
  20.         int counter = 0;
  21.  
  22.         for (int k = 0; k < n; k++)
  23.         {
  24.             array[k] = int.Parse(Console.ReadLine());
  25.         }
  26.  
  27.         for (int i = 1; i <= max; i++)
  28.         {
  29.             currentSum = 0;
  30.             for (int p = 0; p < array.Length; p++)
  31.             {
  32.                 if (((i >> p) & 1) == 1)
  33.                 {
  34.                     currentSum += array[p];
  35.                     subset.Add(array[p]);
  36.                     counter++;
  37.                 }
  38.             }
  39.             if (currentSum == sum && counter == countOfElements)
  40.             {
  41.                 for (int p = 0; p < subset.Count; p++)
  42.                 {
  43.                     Console.Write(subset[p] + " ");
  44.                 }
  45.                 answer++;
  46.                 Console.WriteLine("= {0}", sum);
  47.             }
  48.             counter = 0;
  49.             subset = new List<int>();
  50.         }
  51.         Console.WriteLine(answer + " combinations");
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement