TeMePyT

LiS2

Jun 6th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 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 LIS2
  8. {
  9.     class Program
  10.     {
  11.         public static void Main()
  12.         {
  13.             List<int> sequence = Console.ReadLine().Split().Select(int.Parse).ToList();
  14.             int[] len = new int[sequence.Count];
  15.             int[] prev = new int[sequence.Count];
  16.             List<int> longestSeq = FindLongestIncreasingSubsequence(sequence, len, prev);
  17.             Console.WriteLine( string.Join(" ", longestSeq));
  18.  
  19.         }
  20.  
  21.         public static List<int> FindLongestIncreasingSubsequence(List<int> sequence, int[] len, int[] prev)
  22.         {
  23.             int maxLen = 0;
  24.             int maxIndex = 0;
  25.            
  26.             for (int current = 0; current < sequence.Count; current++)
  27.             {
  28.                 len[current] = 1;
  29.                 prev[current] = -1;
  30.                 for (int i = 0; i < current; i++)
  31.                 {
  32.                     if (sequence[current] > sequence[i] && len[i] + 1 >len[current])
  33.                     {
  34.                         len[current] = len[i] + 1;
  35.                         prev[current] = i;
  36.                     }
  37.                 }
  38.  
  39.                 if (len[current] > maxLen)
  40.                 {
  41.                     maxLen = len[current];
  42.                     maxIndex = current;
  43.                 }
  44.             }
  45.  
  46.             List<int> lis = new List<int>();
  47.             while (maxIndex != -1)
  48.             {
  49.                 lis.Add(sequence[maxIndex]);
  50.                 maxIndex = prev[maxIndex];
  51.             }
  52.  
  53.             lis.Reverse();
  54.             return lis;
  55.         }
  56.     }
  57. }
Add Comment
Please, Sign In to add comment