Advertisement
Guest User

05-Actions

a guest
Jan 16th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _05_Actions
  7. {
  8. class Node
  9. {
  10. public Node(int value, Node previous)
  11. {
  12. this.Value = value;
  13. this.Previous = previous;
  14.  
  15. if (previous != null)
  16. {
  17. this.Previous.Next = this;
  18. }
  19. }
  20.  
  21. public int Value { get; set; }
  22.  
  23. public Node Next { get; set; }
  24.  
  25. public Node Previous { get; set; }
  26. }
  27.  
  28. class Program
  29. {
  30. static void Main(string[] args)
  31. {
  32. var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
  33. var n = input[0];
  34. var m = input[1];
  35. var allNodes = new Dictionary<int, Node>();
  36. var list = new List<int>();
  37. var sb = new StringBuilder();
  38.  
  39. Node head = null;
  40. Node previous = null;
  41.  
  42. for (int i = 0; i < n; i++)
  43. {
  44. var currentNode = new Node(i, previous);
  45. previous = currentNode;
  46.  
  47. if (head == null)
  48. {
  49. head = currentNode;
  50. }
  51.  
  52. allNodes.Add(i, currentNode);
  53. list.Add(i);
  54. }
  55.  
  56. for (int i = 0; i < m; i++)
  57. {
  58. var tokens = Console.ReadLine().Split().Select(int.Parse).ToArray();
  59. var a = tokens[0];
  60. var b = tokens[1];
  61.  
  62. if (list.IndexOf(a) > list.IndexOf(b))
  63. {
  64. var currentNode = allNodes[a];
  65.  
  66. while (currentNode.Next != null && currentNode.Next.Value < b)
  67. {
  68. currentNode = currentNode.Next;
  69. }
  70. MoveBAfterA(allNodes[b], ref currentNode, ref head);
  71.  
  72. list.Remove(b);
  73. list.Insert(list.IndexOf(currentNode.Value) + 1, b);
  74. }
  75. }
  76.  
  77. var node = head;
  78.  
  79. while (node != null)
  80. {
  81. sb.AppendLine(node.Value.ToString());
  82. node = node.Next;
  83. }
  84.  
  85. Console.WriteLine(sb.ToString().TrimEnd());
  86. }
  87.  
  88. private static void MoveBAfterA(Node nodeToBeMoved, ref Node secondNode, ref Node head)
  89. {
  90. var prev = nodeToBeMoved.Previous;
  91. var next = nodeToBeMoved.Next;
  92.  
  93. if (prev == null)
  94. {
  95. next.Previous = null;
  96. head = next;
  97. }
  98. else
  99. {
  100. next.Previous = prev;
  101. prev.Next = next;
  102. }
  103.  
  104. if (secondNode.Next == null)
  105. {
  106. nodeToBeMoved.Next = null;
  107. }
  108. else
  109. {
  110. secondNode.Next.Previous = nodeToBeMoved;
  111. nodeToBeMoved.Next = secondNode.Next;
  112. }
  113. secondNode.Next = nodeToBeMoved;
  114. nodeToBeMoved.Previous = secondNode;
  115. }
  116. }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement