Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class ZeroSubset
- {
- static void Main()
- {
- //Input
- int N = 5;
- int S = 0;
- long[] array = new long[N];
- for (int i = 0; i < N; i++)
- {
- long num = long.Parse(Console.ReadLine());
- array[i] = num;
- }
- //Solution:
- //- Find number of all combinations;
- //- Convert the current combination number to its binary representation;
- //- Mirror the bits in a new string for easier use later;
- //- Take the bit from the current index in the new string and compare it to the desired bit value;
- //- In the end of the loop compare the accumulated sum to the initial input;
- int combinations = (int)Math.Pow(2, N);
- int bit;
- bool subsetFound = false;
- for (int i = 1; i < combinations; i++)
- {
- string comBinary = Convert.ToString(i, 2);
- string reverseBin = "";
- for (int j = comBinary.Length - 1; j >= 0; j--)
- {
- reverseBin += comBinary[j].ToString();
- }
- List<int> currentCombinationNumbers = new List<int>();
- long sum = 0;
- for (int k = 0; k < reverseBin.Length; k++)
- {
- bit = Convert.ToInt32(Convert.ToString(reverseBin[k]));
- if (bit == 1)
- {
- currentCombinationNumbers.Add(Convert.ToInt32(array[k]));
- sum += array[k];
- if (k == (reverseBin.Length - 1) && sum == S && currentCombinationNumbers.Count > 1)
- {
- subsetFound = true;
- //Output if found
- for (int m = 0; m < currentCombinationNumbers.Count; m++)
- {
- if (m < currentCombinationNumbers.Count - 1)
- {
- Console.Write("{0} + ", currentCombinationNumbers[m]);
- }
- else if (m == currentCombinationNumbers.Count - 1)
- {
- Console.WriteLine("{0} = 0 ", currentCombinationNumbers[m]);
- }
- }
- }
- }
- }
- }
- //Output if not found
- if (!subsetFound)
- {
- Console.WriteLine("No zero subset.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement