Advertisement
aslv

Zero Subset

Mar 23rd, 2014
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ZeroSubset
  5. {
  6.     class Subs0
  7.     {
  8.         static void Main()
  9.         {
  10.             const int LEN = 5;
  11.             string pattern;
  12.             int[] a = new int[LEN];
  13.  
  14.             string[] values = Console.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
  15.             for (int i = 0; i < LEN; i++)
  16.             {
  17.                 a[i] = int.Parse(values[i]);
  18.             }
  19.  
  20.             int zerosCount = 0, currentSum;
  21.             List<int> numbers;
  22.             for (int i = 1, m = (int)Math.Pow(2, LEN); i < m; i++)
  23.             {
  24.                 pattern = Convert.ToString(i, 2).PadLeft(LEN, '0');
  25.                 currentSum = 0;
  26.                 numbers = new List<int>();
  27.                 for (int j = 0; j < LEN; j++)
  28.                 {
  29.                     if (pattern[j] == '1')
  30.                     {
  31.                         currentSum += a[j];
  32.                         numbers.Add(a[j]);
  33.                     }
  34.                 }
  35.                 if (currentSum == 0)
  36.                 {
  37.                     zerosCount++;
  38.                     if (numbers.Count > 1)
  39.                     {
  40.                         for (int j = 0; j < numbers.Count - 1; j++)
  41.                         {
  42.                             Console.Write("{0} + ", numbers[j]);
  43.                         }
  44.                         Console.WriteLine("{0} = 0", numbers[numbers.Count - 1]);
  45.                     }
  46.                     else
  47.                     {
  48.                         Console.WriteLine("{0} = 0", numbers[0]);
  49.                     }
  50.                 }
  51.             }
  52.             if (zerosCount > 0)
  53.             {
  54.                 Console.WriteLine("Total: {0} subset(s), whose sum is 0", zerosCount);
  55.             }
  56.             else
  57.             {
  58.                 Console.WriteLine("no zero suset");
  59.             }
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement