Advertisement
ivanov_ivan

LongestNonDecreasingSubsequence

Dec 10th, 2015
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace HW08.LongestNonDecreasingSubsequence
  8. {
  9.     class LongestNonDecreasingSubsequence
  10.     {
  11.         static void Main()
  12.         {
  13.            
  14.             int[] arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
  15.             PrintLNS(arr);
  16.            
  17.         }
  18.         static void PrintLNS(int[] s)
  19.         {
  20.             const int MAX = 100;
  21.             int longestSeqLength = 0;
  22.             int seqLength = s.Length - 1;
  23.             int[,] LNS = new int[MAX, MAX];
  24.             List<string> outputseq = new List<string>();
  25.  
  26.             /* Начално инициализиране */
  27.  
  28.             for(int i = 0; i <= seqLength; i++)
  29.             {
  30.                 for(int j = 1; j <= seqLength; j++)
  31.                 {
  32.  
  33.                     LNS[i , j] = MAX + 1;
  34.                     LNS[i , 0] = -1;
  35.                 }
  36.             }
  37.             /* Основен цикъл */
  38.  
  39.             longestSeqLength = 1;
  40.  
  41.             for(int i = 1; i <= seqLength; i++)
  42.             {
  43.                 for(int j = 1; j <= seqLength; j++)
  44.                 {
  45.                     if(LNS[i - 1 , j - 1] <= s[i] && s[i] <= LNS[i - 1 , j]
  46.                     && LNS[i - 1 , j - 1] <= LNS[i - 1 , j])
  47.                     {
  48.                         LNS[i , j] = s[i];
  49.  
  50.                         if(longestSeqLength < j)
  51.                         {
  52.                             longestSeqLength = j;
  53.                         }
  54.                     }
  55.                     else
  56.                     {
  57.                         LNS[i , j] = LNS[i - 1 , j];
  58.                     }
  59.                 }
  60.             }
  61.             do
  62.             {
  63.             if(LNS[seqLength , longestSeqLength] == LNS[seqLength - 1 , longestSeqLength])
  64.             {
  65.                     seqLength--;
  66.             }
  67.             else
  68.             {
  69.                outputseq.Add(Convert.ToString(s[seqLength]));
  70.                 longestSeqLength--;
  71.             }
  72.  
  73.             } while(seqLength > 0);
  74.  
  75.             for(int i = outputseq.Count - 1; i >= 0 ; i--)
  76.             {
  77.                 Console.Write(outputseq[i] + " ");
  78.             }
  79.  
  80.             Console.WriteLine();
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement