Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class LongestNonDecreasingSubsequence
- {
- static int[] SolveInput(string input)
- {
- // read the input and split by space
- string[] numbers = input.Split(' '.ToString().ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
- int[] nums = new int[numbers.Length];
- // save values in array
- for (int i = 0; i < nums.Length; i++)
- {
- nums[i] = int.Parse(numbers[i]);
- }
- return nums;
- }
- static List<List<int>> SolvePairs(int[] numbers,ref List<int> numLastIndex)
- {
- // save all posible pairs of non-decreasing elements
- List<List<int>> numSequences = new List<List<int>>();
- for (int i = 0; i < numbers.Length; i++)
- {
- for (int j = i + 1; j < numbers.Length; j++)
- {
- if (numbers[i] <= numbers[j])
- {
- List<int> pairs = new List<int>();
- pairs.Add(numbers[i]);
- pairs.Add(numbers[j]);
- numLastIndex.Add(j);
- numSequences.Add(pairs);
- }
- }
- }
- return numSequences;
- }
- static void SolveAddMoreDigits(ref List<List<int>> numSequences, List<int> numLastIndex, int[] nums)
- {
- for (int i = 0; i < numLastIndex.Count; i++)
- {
- if (numLastIndex[i] < nums.Length - 2)
- {
- int count = 1;
- for (int j = numLastIndex[i + 1]; j < nums.Length; j++)
- {
- if (numSequences[i][count] <= nums[j])
- {
- numSequences[i].Add(nums[j]);
- count++;
- }
- else if (numSequences[i][count] > nums[j] && numSequences[i][count - 1] <= nums[j])
- {
- numSequences[i].RemoveAt(numSequences[i].Count - 1);
- numSequences[i].Add(nums[j]);
- }
- }
- }
- }
- }
- static void Main()
- {
- /*
- * 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.
- */
- string input = Console.ReadLine();
- int[] nums = SolveInput(input);
- List<int> numLastIndex = new List<int>();
- List<List<int>> numSequences = SolvePairs(nums, ref numLastIndex);
- SolveAddMoreDigits(ref numSequences, numLastIndex, nums);
- if (numSequences.Count == 0)
- {
- List<int> numSeq = new List<int>();
- numSeq.Add(nums[0]);
- numSequences.Add(numSeq);
- }
- var max = numSequences.Max(e=>e.Count);
- var maxSeq = numSequences.Where(e=>e.Count == max).ToList();
- foreach (var item in maxSeq[0])
- {
- Console.Write("{0} ",item);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement