Advertisement
mivak

LongestNonDecreasingSubsequence

Mar 31st, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. namespace Task8LongestNonDecreasingSubsequence
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. class Task8LongestNonDecreasingSubsequence
  6. {
  7. static void Main()
  8. {
  9. /*Write a program that reads a sequence of integers and finds in it the longest
  10. * non-decreasing subsequence. In other words, you should remove a minimal number
  11. * of numbers from the starting sequence, so that the resulting sequence is non-decreasing.
  12. * In case of several longest non-decreasing sequences, print the leftmost of them.
  13. * The input and output should consist of a single line, holding integer numbers separated by a space.*/
  14.  
  15. Console.WriteLine("Please enter some numbers separated by a single space");
  16. string text = Console.ReadLine();
  17. char[] separators = { ' ' };
  18. string[] words = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  19. List<int> numbers = new List<int>();
  20. List<int> sequence = new List<int>();
  21. List<int> maxSequence = new List<int>();
  22.  
  23. for (int i = 0; i < words.Length; i++)
  24. {
  25. numbers.Add(int.Parse(words[i]));
  26. }
  27.  
  28. for (int i = 0; i < numbers.Count - 1; i++)
  29. {
  30. int current = numbers[i];
  31. sequence.Add(numbers[i]);
  32.  
  33. for (int j = i; j < numbers.Count - 1; j++)
  34. {
  35.  
  36. if (current <= numbers[j + 1])
  37. {
  38. sequence.Add(numbers[j + 1]);
  39. current = numbers[j + 1];
  40. }
  41. }
  42.  
  43. if (sequence.Count > maxSequence.Count)
  44. {
  45. maxSequence = new List<int>();
  46. maxSequence.Add(sequence[0]);
  47. for (int k = 0; k < sequence.Count - 1; k++)
  48. {
  49.  
  50. if (sequence[k] <= sequence[k + 1])
  51. {
  52. maxSequence.Add(sequence[k + 1]);
  53. }
  54. numbers.Remove(sequence[k + 1]);
  55. }
  56. }
  57. sequence = new List<int>();
  58. }
  59.  
  60. for (int i = 0; i < maxSequence.Count; i++)
  61. {
  62. Console.Write(maxSequence[i] + " ");
  63. }
  64. }
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement