annstasi

Untitled

Jun 9th, 2021
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. // Вставьте сюда финальное содержимое файла LongestCommonSubsequenceCalculator.cs
  2. using System;
  3. using System.Collections.Generic;
  4.  
  5. namespace Antiplagiarism
  6. {
  7. public static class LongestCommonSubsequenceCalculator
  8. {
  9. public static List<string> Calculate(List<string> first, List<string> second)
  10. {
  11. var opt = CreateOptimizationTable(first, second);
  12. return RestoreAnswer(opt, first, second);
  13. }
  14.  
  15. private static int[,] CreateOptimizationTable(List<string> first, List<string> second)
  16. {
  17. var count1 = first.Count;
  18. var count2 = second.Count;
  19.  
  20. var opt = new int[count1 + 1, count2 + 1];
  21. opt[0, 0] = 0;
  22.  
  23. /*Граничные случаи тривиальны: opt[0, i2] = 0, opt[i1, 0] = 0 для любых i1 и i2*/
  24. for (var i = 1; i <= count1; ++i) opt[i, 0] = 0;
  25. for (var i = 1; i <= count2; ++i) opt[0, i] = 0;
  26.  
  27. for (int i = 1; i <= count1; ++i)
  28.  
  29. for (int j = 1; j <= count2; ++j)
  30. {
  31. /*Рассматриваем совпадение токенов*/
  32. if (first[i - 1] == second[j - 1])
  33. opt[i, j] = opt[i - 1, j - 1] + 1;
  34. else
  35. opt[i, j] = Math.Max(opt[i - 1, j], opt[i, j - 1]);
  36. }
  37.  
  38. var result = opt;
  39. return result;
  40. }
  41.  
  42. private static List<string> RestoreAnswer(int[,] opt, List<string> first, List<string> second)
  43. {
  44. var r = new List<string>();
  45.  
  46. var count1 = first.Count;
  47. var count2 = second.Count;
  48.  
  49. while (opt[count1, count2] != 0)
  50. {
  51. if (opt[count1 - 1, count2] >= opt[count1, count2])
  52. {
  53. if (opt[count1 - 1, count2] >= opt[count1, count2 - 1])
  54. count1--;
  55. else count2--;
  56. }
  57.  
  58. else if (opt[count1, count2 - 1] >= opt[count1, count2])
  59. {
  60. if (opt[count1 - 1, count2] >= opt[count1, count2 - 1])
  61. count1--;
  62. else count2--;
  63. }
  64.  
  65. else
  66. {
  67. r.Add(first[count1 - 1]);
  68. opt[count1, count2]--;
  69. count1--; count2--;
  70. }
  71. }
  72.  
  73. r.Reverse();
  74. return r;
  75. }
  76. }
  77. }
  78.  
  79.  
Advertisement
Add Comment
Please, Sign In to add comment