alexmitev

LongestNonDecreasingSequence

Nov 7th, 2015
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. //Problem 5.    * Longest Non-Decreasing Subsequence
  2. //Write a program that reads a sequence of integers and finds in it the longest non-decreasing subsequence. In other words, you //should remove a minimal number of numbers from the starting sequence, so that the resulting sequence is non-decreasing. In case //of several longest non-decreasing sequences, print the leftmost of them. The input and output should consist of a single line, //holding integer numbers separated by a space.
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7.  
  8.     class Test
  9.     {
  10.         static void Main()
  11.         {
  12.         var input = Console.ReadLine().Split().Select(int.Parse).ToArray();  
  13.         var resultList = new List<int>();
  14.         int lenght = 0;
  15.         string  str = "";
  16.         string sequence = "";
  17.        
  18.         int combinations = (int)Math.Pow(2, (input.Length));
  19.         Console.WriteLine();
  20.            
  21.             for(int i = 1; i <= combinations; i++)
  22.             {
  23.                 int[] bits = new int[input.Length];
  24.  
  25.                 for (int k = 0; k < input.Length; k ++)
  26.                 {
  27.                     int temp = 0;
  28.                     bits[k] = (i >> k) & 1;
  29.                     temp = bits[k] * input[k];
  30.                     if (temp != 0)
  31.                     {
  32.                         resultList.Add(temp);
  33.                     }
  34.  
  35.                 }
  36.                 int num = 0;
  37.                 int currentcount = 0;
  38.                 for(int j  = 0; j < resultList.Count; j++)
  39.                 {
  40.                     if (resultList[j] >= num)
  41.                     {
  42.                         str += resultList[j] + " ";
  43.                         currentcount++;
  44.                         num = resultList[j];
  45.                     }
  46.                 }
  47.                 if  (currentcount > lenght)
  48.                 {
  49.                     sequence = str;
  50.                     lenght = currentcount;
  51.                 }
  52.                 resultList.Clear();
  53.                 str = string.Empty;
  54.             }
  55.             Console.WriteLine(sequence);
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment