Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. Scanner s = new Scanner(System.in);
  9. int n = s.nextInt();
  10. int[] a = new int[n];
  11. int[] b = new int[n];
  12. for (int i = 0; i < n; i++) {
  13. a[i] = b[n - i - 1] = s.nextInt();
  14. }
  15. int[] result1 = LongestIncreasingSubsequence(a, n);
  16. int[] result2 = LongestIncreasingSubsequence(b, n);
  17. if (result2.length >= result1.length) {
  18. System.out.println(result2.length);
  19. for (int i : result2)
  20. System.out.print(i + " ");
  21. } else {
  22. System.out.println(result1.length);
  23. for (int i = result1.length - 1; i >= 0; i--)
  24. System.out.print(result1[i] + " ");
  25. }
  26. }
  27.  
  28. static int GetCeilIndex(int arr[], int T[], int l, int r, int key) {
  29.  
  30. while (r - l > 1) {
  31. int m = l + (r - l) / 2;
  32. if (arr[T[m]] >= key)
  33. r = m;
  34. else
  35. l = m;
  36. }
  37. return r;
  38. }
  39.  
  40. static int[] LongestIncreasingSubsequence(
  41. int arr[], int n) {
  42.  
  43.  
  44. int tailIndices[] = new int[n];
  45.  
  46.  
  47. Arrays.fill(tailIndices, 0);
  48.  
  49. int prevIndices[] = new int[n];
  50.  
  51.  
  52. Arrays.fill(prevIndices, -1);
  53.  
  54. int len = 1;
  55.  
  56. for (int i = 1; i < n; i++) {
  57. if (arr[i] < arr[tailIndices[0]])
  58.  
  59. tailIndices[0] = i;
  60.  
  61. else if (arr[i] >
  62. arr[tailIndices[len - 1]]) {
  63.  
  64. prevIndices[i] = tailIndices[len - 1];
  65. tailIndices[len++] = i;
  66. } else {
  67.  
  68. int pos = GetCeilIndex(arr,
  69. tailIndices, -1, len - 1, arr[i]);
  70.  
  71. prevIndices[i] = tailIndices[pos - 1];
  72. tailIndices[pos] = i;
  73. }
  74. }
  75.  
  76.  
  77. int[] res = new int[len];
  78. int j = 0;
  79. for (int i = tailIndices[len - 1]; i >= 0 && j < len; i = prevIndices[i])
  80. res[j++] = arr[i];
  81.  
  82. return res;
  83. }
  84. }
  85.  
  86.  
  87. 100
  88. 119 345 249 442 461 302 186 9 71 122 368 119 264 184 368 59 256 17 498 138 46 23 101 105 426 484 315 375 269 146 57 75 359 38 211 84 135 186 438 146 457 243 362 406 44 195 134 221 115 459 477 58 158 80 86 360 9 127 68 145 88 75 460 220 383 134 146 324 224 202 42 450 111 61 459 489 273 403 136 52 364 44 75 87 13 390 354 234 63 103 76 163 60 302 128 394 314 2 108 197
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement