Advertisement
Guest User

scmax

a guest
Feb 24th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. MODULE upseq;
  2.  
  3. IMPORT In, Out;
  4.  
  5. CONST MAX = 10000;
  6.  
  7. VAR xList, yList, lis, prev : ARRAY MAX OF INTEGER;
  8. VAR n, k : INTEGER;  (* n is the size of xList and yList; k is the ending index of the longest increasing subsequence *)
  9.  
  10.  
  11. (* reads the input and saves the lists into xList and yList *)
  12.  
  13. PROCEDURE Input;
  14.   VAR x, y : INTEGER;
  15. BEGIN
  16.   n := 0;
  17.   LOOP
  18.     IF ~In.Done THEN EXIT END;
  19.     In.Int(x);
  20.     In.Int(y);
  21.     xList[n] := x;
  22.     yList[n] := y;
  23.     n := n+1
  24.   END
  25. END Input;
  26.  
  27.  
  28. (* dynamic quadratic algorithm to find the Longest Increasing Subsequence *)
  29.  
  30. PROCEDURE LIS;
  31.   VAR i, j: INTEGER;
  32. BEGIN
  33.   lis[0] := 1;
  34.   prev[0] := -1;
  35.   k := 0;
  36.  
  37.   (* finds the length of the longest increasing subsequence in yList[0..i] *)
  38.   FOR i := 1 TO n-1 DO
  39.     lis[i] := 1;
  40.     prev[i] := -1;
  41.     FOR j := 0 TO i-1 DO
  42.       IF (yList[j] < yList[i]) & (lis[j] >= lis[i]) THEN
  43.         lis[i] := 1 + lis[j];
  44.         prev[i] := j;
  45.         IF lis[i] > lis[k] THEN
  46.           k := i;
  47.         END
  48.       END
  49.     END
  50.   END
  51. END LIS;
  52.  
  53.  
  54. (* recursive proc that prints the longest increasing subsequence with the use of prev and lis *)
  55.  
  56. PROCEDURE Print(x : INTEGER);
  57. BEGIN
  58.   IF x = -1 THEN
  59.     RETURN
  60.   END;
  61.   Print(prev[x]);
  62.   Out.Int(xList[x], 0); Out.String(" "); Out.Int(yList[x], 0); Out.Ln
  63.  
  64. END Print;
  65.  
  66. BEGIN
  67.   Input;
  68.   LIS;
  69.   IF n # 0 THEN
  70.     Print(k)
  71.   ELSE
  72.     Out.String("Empty or invalid input"); Out.Ln
  73.   END
  74. END upseq.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement