static void BFS(IDictionary<int, Node> nodes, Node node) { var q = new Queue<Node>(); q.Enqueue(node); while(q.Count > 0){ var n = q.Dequeue(); if (n.Processed) continue; foreach(var edge in n.Edges){ var nodeY = nodes[edge]; if (nodeY.Processed) continue; var distance = n.Distance + 6; if (nodeY.Distance == -1 || (nodeY.Distance>0 && distance < nodeY.Distance)){ nodeY.Distance = distance; } q.Enqueue(nodeY); } n.Processed = true; } }
public static Node<int> FindCommonAncestor(Node<int> node, int i, int j) { if (node == null) { return null; } else if (node.Left != null && (node.Left.Element == i || node.Left.Element == j)) { return node; } else if (node.Right != null && (node.Right.Element == i || node.Right.Element == j)) { return node; } else { Node<int> left = FindCommonAncestor(node.Left, i, j); Node<int> right = FindCommonAncestor(node.Right, i, j); if (left != null && right != null) { return node; } else { Node<int> elem = left == null ? right : left; return elem; } } }
public void push(int item) { Node newItem = new Node(); newItem.item = item; newItem.next = top; top = newItem; n++; }
public void ReverseTest() { var node1 = new Node() {Data = 3,Next = null}; var node2 = new Node() {Data = 2,Next = node1}; var node3 = new Node() {Data = 1,Next = node2}; Assert.AreEqual(3,node3.Next.Next.Data); var olo = Reverse(node3); Assert.AreEqual(1,Reverse(node3).Next.Next.Data); }
// CRUD = create, read, update, delete = insert, read/find, update?, remove // read: in-order, pre-order (copy tree), post-order (delete tree). recursive & non-recursive // find binary-search-like: find exact, find closest, find greatest smaller, find smallest greater // find tree-specific: lowest common ancestor, in-order predecessor & successor // transform: bst <-> doubly linked list // definition check: is a tree bst? public void Insert(int val) { if (root == null) { root = new Node(val); return; } // Option 1: keep track of both the parent and the child (the position for new element) Node parent = root; Node child = root; bool right = true; while (child != null) { parent = child; right = (child.val <= val); child = right ? child.right : child.left; } if (right) parent.right = new Node(val); else parent.left = new Node(val); /*// Option 2: just keep track of the parent node. Simple idea but a bit more lengthy implementation Node parent = root; while (parent != null) { if (parent.val <= val) { if (parent.right == null) { parent.right = new Node(val); return; } else { parent = parent.right; } } else { if (parent.left == null) { parent.left = new Node(val); return; } else { parent = parent.left; } } } */ }
public static Node FindNode(int valueBeingSearchedFor, Node currentNode) { if (currentNode == null) return null; else if (valueBeingSearchedFor == currentNode.Value) return currentNode; else if (valueBeingSearchedFor < currentNode.Value) return FindNode(valueBeingSearchedFor, currentNode.LeftChild); else return FindNode(valueBeingSearchedFor, currentNode.RightChild); }
public int pop() { if (n == 0) { throw new Exception("Stack underflow"); } int toBeRemoved = top.item; top = top.next; n--; return toBeRemoved; }
public static Node BuildTree(List<int> data, int start, int end) { Node leftChild = null; Node rightChild = null; int mid = (start + end) / 2; if (start < end) { leftChild = BuildTree(data, start, mid); rightChild = BuildTree(data, mid + 1, end); } var parent = new Node(data[mid], leftChild, rightChild); leftChild.Parent = parent; rightChild.Parent = parent; return parent; }
public static void DeleteNode(int valueToDelete, Node startingNode) { Node nodeToDelete = FindNode(valueToDelete, startingNode); Node selectedLeaf = null; // Find the leaf to replace the deleted node. if (nodeToDelete.RightChild != null) { Node cursorNode = nodeToDelete.RightChild; while (true) { if (cursorNode.LeftChild != null) cursorNode = cursorNode.LeftChild; else { selectedLeaf = cursorNode; break; } } } else selectedLeaf = nodeToDelete.LeftChild; // Change the reference to nodeToDelete in its parent's child attribute if (nodeToDelete.Value < nodeToDelete.Parent.Value) nodeToDelete.Parent.LeftChild = selectedLeaf; else nodeToDelete.Parent.RightChild = selectedLeaf; nodeToDelete.Parent = null; // Remove the reference to selectedLeaf from its original parent if (selectedLeaf.Value < selectedLeaf.Parent.Value) selectedLeaf.Parent.LeftChild = null; else selectedLeaf.Parent.RightChild = null; // Give selected leaf a new parent selectedLeaf.Parent = nodeToDelete.Parent; // Selected leaf is assigned new children selectedLeaf.LeftChild = nodeToDelete.LeftChild; selectedLeaf.RightChild = nodeToDelete.RightChild; // if nodeToDelete has children, reassign their parent references if (nodeToDelete.LeftChild != null) nodeToDelete.LeftChild.Parent = selectedLeaf; if (nodeToDelete.RightChild != null) nodeToDelete.RightChild.Parent = selectedLeaf; // Finish isolating nodeToDelete so it can get picked up by Garbage collection. nodeToDelete.LeftChild = null; nodeToDelete.RightChild = null; }
public Node<int> add(int[] array, int start, int end) { if (end < start) { return null; } int mid = (start + end) / 2; Node<int> node = new Node<int>(array[mid]); node.Left = add(array, start, mid - 1); node.Right = add(array, mid + 1, end); return node; }
public Node Reverse(Node root) { Node current = root; Node previous = null; Node tmp = null; while (current!=null) { tmp = current; current = current.Next; tmp.Next=previous; previous = tmp; } return previous; }
private static Boolean Contains(Node<int> node, int elem) { if (node == null) { return false; } else if (node.Element == elem) { return true; } else { return Contains(node.Left, elem) || Contains(node.Right, elem); } }
static Node CreateLinkedListFromArray(int[] a) { if (a == null || a.Length == 0) { Console.WriteLine("Input array is null or empty"); return null; } Node head = new Node(a[0]); Node p = head; for (int i=1; i<a.Length; i++) { p.next = new Node(a[i]); p = p.next; } return head; }
// Реализация BFS алгоритма. private void bfs(int s) { minimalPathList = new int[container.Size]; Queue<int> queue = new Queue<int>(); Node[] nodes = new Node[container.Size]; for (int i = 0; i < container.Size; ++i) { minimalPathList[i] = -1; nodes[i] = new Node(); } nodes[s].length = 0; nodes[s].visited = true; minimalPathList[s] = 0; queue.Enqueue(s); while (queue.Count != 0) { int t = queue.Dequeue(); List<int> tmp = container.Neighbourship[t]; for (int i = 0; i < tmp.Count; ++i) { int e = tmp[i]; if (nodes[e].visited == false) { nodes[e].visited = true; nodes[e].length = nodes[t].length + 1; queue.Enqueue(e); minimalPathList[e] = nodes[e].length; } } } }
public Node(Node node) { this.suffixNode = node.suffixNode; }
public Node(int val, Node leftChild, Node rightChild) { Value = val; LeftChild = leftChild; RightChild = rightChild; if (leftChild != null || rightChild != null) this.BalanceFactor = ((leftChild != null) ? LeftChild.BalanceFactor : 0) - ((rightChild != null) ? RightChild.BalanceFactor : 0) + 1; }
// Выполняет подсчет сразу 3 свойств - средняя длина пути, диаметр и пути между вершинами. // Нужно вызвать перед получением этих свойств не изнутри. private void CountEssentialOptions() { if (edgesBetweenNeighbours.Count == 0) { for (int i = 0; i < container.Size; ++i) edgesBetweenNeighbours.Add(-1); } double avg = 0; int diametr = 0, k = 0; for (int i = 0; i < container.Size; ++i) { for (int j = i + 1; j < container.Size; ++j) { int way = MinimumWay(i, j); if (way == -1) continue; if (pathDistribution.ContainsKey(way)) pathDistribution[way]++; else pathDistribution.Add(way, 1); if (way > diametr) diametr = way; avg += way; ++k; } } Node[] nodes = new Node[container.Size]; for (int t = 0; t < container.Size; ++t) nodes[t] = new Node(); BFS(container.Size - 1, nodes); avg /= k; avgPath = avg; diameter = diametr; }
// Возвращает длину минимальной пути между данными вершинами. private int MinimumWay(int i, int j) { if (i == j) return 0; Node[] nodes = new Node[container.Size]; for (int k = 0; k < container.Size; ++k) nodes[k] = new Node(); BFS(i, nodes); return nodes[j].lenght; }
// Реализация BFS алгоритма. private void BFS(int i, Node[] nodes) { nodes[i].lenght = 0; nodes[i].ancestor = 0; bool b = true; Queue<int> q = new Queue<int>(); q.Enqueue(i); int u; if (edgesBetweenNeighbours[i] == -1) edgesBetweenNeighbours[i] = 0; else b = false; while (q.Count != 0) { u = q.Dequeue(); List<int> l = container.Neighbourship[u]; for (int j = 0; j < l.Count; ++j) if (nodes[l[j]].lenght == -1) { nodes[l[j]].lenght = nodes[u].lenght + 1; nodes[l[j]].ancestor = u; q.Enqueue(l[j]); } else { if (nodes[u].lenght == 1 && nodes[l[j]].lenght == 1 && b) { ++edgesBetweenNeighbours[i]; } } } if (b) edgesBetweenNeighbours[i] /= 2; }
// Возвращает число циклов 4, которые содержат данную вершину. private int CalculatCycles4(int i) { Node[] nodes = new Node[container.Size]; for (int k = 0; k < container.Size; ++k) nodes[k] = new Node(); int cyclesOfOrderi4 = 0; nodes[i].lenght = 0; nodes[i].ancestor = 0; Queue<int> q = new Queue<int>(); q.Enqueue(i); int u; while (q.Count != 0) { u = q.Dequeue(); List<int> l = container.Neighbourship[u]; for (int j = 0; j < l.Count; ++j) if (nodes[l[j]].lenght == -1) { nodes[l[j]].lenght = nodes[u].lenght + 1; nodes[l[j]].ancestor = u; q.Enqueue(l[j]); } else { if (nodes[u].lenght == 2 && nodes[l[j]].lenght == 1 && nodes[u].ancestor != l[j]) { SortedList<int, int> cycles4I = new SortedList<int, int>(); cyclesOfOrderi4++; } } } return cyclesOfOrderi4; }
public Node(int val) { this.val = val; next = null; }
// Возвращается распределение чисел связанных подграфов в графе. public override SortedDictionary<int, int> GetConnSubGraph() { var connectedSubGraphDic = new SortedDictionary<int, int>(); Queue<int> q = new Queue<int>(); var nodes = new Node[container.Size]; for (int i = 0; i < nodes.Length; i++) nodes[i] = new Node(); var list = new List<int>(); for (int i = 0; i < container.Size; i++) { int order = 0; q.Enqueue(i); while (q.Count != 0) { var item = q.Dequeue(); if (nodes[item].lenght != 2) { if (nodes[item].lenght == -1) { order++; } list = container.Neighbourship[item]; nodes[item].lenght = 2; for (int j = 0; j < list.Count; j++) { if (nodes[list[j]].lenght == -1) { nodes[list[j]].lenght = 1; order++; q.Enqueue(list[j]); } } } } if (order != 0) { if (connectedSubGraphDic.ContainsKey(order)) connectedSubGraphDic[order]++; else connectedSubGraphDic.Add(order, 1); } } return connectedSubGraphDic; }
static Node Merge(Node p, Node q) { //PrintLinkedList(p); //PrintLinkedList(q); Node dummy = new Node(0); Node tail = dummy; while (p != null && q != null) { if (p.val <= q.val) { tail.next = p; p = p.next; } else { tail.next = q; q = q.next; } tail = tail.next; } while (p != null) { tail.next = p; tail = p; p = p.next; } while (q != null) { tail.next = q; tail = q; q = q.next; } tail.next = null; // make sure list ends with null return dummy.next; }
public static void PrintLinkedList(Node head, string msg) { if (head == null) { Console.WriteLine("Head is null"); } Console.Write(msg + " "); while (head != null) { Console.Write("{0}, ", head.val); head = head.next; } Console.WriteLine(); }
//! Merge sort a singly linked list. //! Same partition method as merge sorting an array. //! A major difference is don't have to use auxilary array, can just redirect pointers public static Node MergeSort(Node start) { if (start == null) return null; // stop case of single element if (start.next == null) { return start; } // list has >= 2 elements // find mid node Node mid = start; Node fast = start; while (fast != null && fast.next != null && fast.next.next != null) { mid = mid.next; fast = fast.next.next; } Node list2 = mid.next; mid.next = null; // make sure list ends with null Node p = MergeSort(start); Node q = MergeSort(list2); Node head = Merge(p, q); return head; }
public static void InsertValue(int valueToInsert, Node currentNode) { while (true) { if (valueToInsert < currentNode.Value) { if (currentNode.LeftChild != null) currentNode = currentNode.LeftChild; else currentNode.LeftChild = new Node(valueToInsert, null, null); break; } else { if (currentNode.RightChild != null) currentNode = currentNode.RightChild; else currentNode.RightChild = new Node(valueToInsert, null, null); break; } } }
public static int SplitEdge(Suffix s, string theString, Dictionary<int, Edge> edges, Dictionary<int, Node> nodes,ref Edge edge) { Remove(edge); Edge newEdge = new Edge(theString, edge.indexOfFirstCharacter, edge.indexOfFirstCharacter + s.indexOfLastCharacter - s.indexOfFirstCharacter, s.originNode); Edge.Insert(newEdge); if (nodes.ContainsKey(newEdge.endNode)) { nodes[newEdge.endNode].suffixNode = s.originNode; } else { Node newNode = new Node(); newNode.suffixNode = s.originNode; nodes.Add(newEdge.endNode, newNode); } edge.indexOfFirstCharacter += s.indexOfLastCharacter - s.indexOfFirstCharacter + 1; edge.startNode = newEdge.endNode; Edge.Insert(edge); return newEdge.endNode; }
static string ExecuteTestCase(int iTest) { Console.WriteLine("####################"); Console.WriteLine("Start Case #{0}", iTest); //Read Data var arr = input[inputIndx].Split(' '); inputIndx++; var numOfNodes = Convert.ToInt32(arr[0]); var numOfEdges = Convert.ToInt32(arr[1]); Console.WriteLine("# of nodes: {0}", numOfNodes); Console.WriteLine("# of edges: {0}", numOfEdges); var sw = Stopwatch.StartNew(); var edges = new int[numOfNodes, numOfNodes]; for(int i=0;i<numOfNodes;i++) for(int j=0;j<numOfNodes;j++) edges[i,j] = 0; for(var iEdge = 0; iEdge < numOfEdges; iEdge++){ var arrEdge = input[inputIndx].Split(' '); inputIndx++; var xEdge = Convert.ToInt32(arrEdge[0]); var yEdge = Convert.ToInt32(arrEdge[1]); edges[xEdge - 1, yEdge - 1] = 1; edges[yEdge - 1, xEdge - 1] = 1; } var edgesFound = 0; var nodes = new Dictionary<int, Node>(); //var edgeDuplicates = 0; for(var i = 1; i<=numOfNodes;i++){ var node = new Node(i); for (int e = 1;e<=numOfNodes;e++){ if (edges[i - 1, e -1] == 1){ node.Edges.Add(e); edgesFound++; //Console.Write("{0}->{1} ", i, e); } } nodes.Add(i, node); } Console.WriteLine("edge founding time: {0}", sw.Elapsed.TotalSeconds); Console.WriteLine("# of edges found: {0}", edgesFound/2); //Console.WriteLine("# of edge duplicates found: {0}", edgeDuplicates); var startNodeIndx = Convert.ToInt32(input[inputIndx]); inputIndx++; //Process nodes[startNodeIndx].Distance = 0; sw = Stopwatch.StartNew(); BFS(nodes, nodes[startNodeIndx]); sw.Stop(); Console.WriteLine("bfs time: {0}", sw.Elapsed.TotalSeconds); var sb = new StringBuilder(); foreach(int key in nodes.Keys){ if (key != startNodeIndx) sb.AppendFormat("{0} ", nodes[key].Distance); } Console.WriteLine("End Case #{0}", iTest); return sb.ToString().Trim(); }
void InOrderRecursive(Node x) { if (x == null) return; InOrderRecursive(x.left); Console.Write("{0}, ", x.val); InOrderRecursive(x.right); }