500 likes | 665 Views
0. 4. 1. 3. 2. 2. 1. 3. 0. Josephus problem. N=5, K=3. (J(N-1, K) + K) mod N = J(N, K) J(1, K) = 0. Ak K=2 a N = b0b1b2b3...bn J(N, 2) = b1b2b3...bnb0. http://www.cut-the-knot.org/recurrence/flavius.shtml. Stack - interface. public interface Stack<E> { public int size ();
E N D
0 4 1 3 2 2 1 3 0 Josephus problem N=5, K=3 (J(N-1, K) + K) mod N = J(N, K) J(1, K) = 0 Ak K=2 a N = b0b1b2b3...bn J(N, 2) = b1b2b3...bnb0 http://www.cut-the-knot.org/recurrence/flavius.shtml
Stack - interface publicinterfaceStack<E> { public intsize(); public booleanisEmpty(); public E top() throwsEmptyStackException; public voidpush (E element) throwsFullStackException; public E pop() throwsEmptyStackException; } • ArrayStack<Integer> A = newArrayStack<Integer>(100); • A.push(7); • o = A.pop();
Stack – implementation publicclassArrayStack<E> implementsStack<E> { protected int capacity; public staticfinal int CAPACITY = 1000; protected E S[]; protected int top = -1; public ArrayStack(int cap) { capacity = cap; S =(E[]) newObject[capacity]; } public voidpush(E element) throwsFullStackException { if(size() == capacity) thrownew FullStackException(“full."); S[++top] = element; } public E pop() throwsEmptyStackException { E element; if(isEmpty()) thrownewEmptyStackException("empty."); element = S[top]; S[top--] = null; returnelement; }
Queue - interface publicinterfaceQueue<E> { public intsize(); public booleanisEmpty(); public E front() throwsEmptyQueueException; public voidenqueue (E element); public E dequeue() throwsEmptyQueueException; }
Node publicclassNode<E> { private E element; private Node<E> next; public Node() {this(null, null); } public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { returnelement; } public Node<E> getNext() { returnnext; } public voidsetElement(E newElem) { element = newElem; } public voidsetNext(Node<E> newNext) { next = newNext; } }
Queue public voidenqueue(E elem) { Node<E> node = newNode<E>(); node.setElement(elem); node.setNext(null); if(size == 0) front = node; else rear.setNext(node); rear = node; size++; } public E dequeue() throwsEmptyQueueException { if(size == 0) thrownewEmptyQueueException("Queue is empty."); E tmp = front.getElement(); front = front.getNext(); size--; if(size == 0) rear = null; returntmp; }
Queue public voidenqueue(E elem) { Node<E> node = newNode<E>(); node.setElement(elem); if (size == 0) node.setNext(node); else { node.setNext(rear.getNext()); rear.setNext(node); } rear = node; size++; } public E dequeue() throwsEmptyQueueException { if(size == 0) thrownewEmptyQueueException("Queue is empty."); size--; E tmp = rear.getNext().getElement(); if (size == 0) rear = null; else read.setNext(rear.getNext().getNext()); returntmp; }
Node - Stack publicclassNodeStack<E> implementsStack<E> { protected Node<E> top; protected int size; public NodeStack() { top = null; size = 0; } public voidpush(E elem) { Node<E> v = newNode<E>(elem, top); top = v; size++; } public E top() throwsEmptyStackException { if(isEmpty()) thrownewEmptyStackException("empty."); returntop.getElement(); } public E pop() throwsEmptyStackException { if(isEmpty()) thrownewEmptyStackException("empty."); E temp = top.getElement(); top = top.getNext(); size--; returntemp; } }
Balík - interface publicinterfaceDeque<E> { public intsize(); public booleanisEmpty(); public E getFirst() throwsEmptyDequeException; public E getLast() throwsEmptyDequeException; public voidaddFirst (E element); public voidaddLast (E element); public E removeFirst() throwsEmptyDequeException; public E removeLast() throwsEmptyDequeException; }
DLNode publicclass DLNode<E> { private E element; private DLNode<E> prev, next; public DLNode() { this(null, null, null); } public DLNode(E e, Node<E> p, Node<E> n) { element = e; next = n; prev = p; } public E getElement() { returnelement; } public Node<E> getNext() { returnnext; } public voidsetElement(E newElem) { element = newElem; } . . . .
Balík – implementácia publicclassNodeDeque<E> implementsDeque<E> { protected DLNode<E> header, trailer; protected int size; public NodeDeque() { header = newDLNode<E>(); trailer = newDLNode<E>(); header.setNext(trailer); trailer.setPrev(header); size = 0; } public E getFirst() throwsEmptyDequeException { if(isEmpty()) thrownewEmptyDequeException("Deque is empty."); returnheader.getNext().getElement(); }
Balík - implementácia public voidaddFirst(E o) { DLNode<E> second = header.getNext(); DLNode<E> first = newDLNode<E>(o, header, second); second.setPrev(first); header.setNext(first); size++; } public E removeLast() throwsEmptyDequeException { if(isEmpty()) thrownewEmptyDequeException("Deque is empty."); DLNode<E> last = trailer.getPrev(); E o = last.getElement(); DLNode<E> secondtolast = last.getPrev(); trailer.setPrev(secondtolast); secondtolast.setNext(trailer); size--; returno; }
IndexList - interface publicinterfaceIndexList<E> { public intsize(); public booleanisEmpty(); public voidadd(int i, E e) throwsIndexOutOfBoundsException; public E get(int i) throwsIndexOutOfBoundsException; public E remove(int i) throwsIndexOutOfBoundsException; public E set(int i, E e) throwsIndexOutOfBoundsException; }
IndexList - implementation publicclassArrayIndexList<E> implementsIndexList<E> { private E[] A; private int capacity = 16; private int size = 0; public ArrayIndexList() { A =(E[]) newObject[capacity]; } public voidadd(int r, E e) throwsIndexOutOfBoundsException { checkIndex(r, size() + 1); if(size == capacity) { // an overflow capacity *= 2; E[] B =(E[]) newObject[capacity]; for(int i=0; i<size; i++) B[i] = A[i]; A = B; } for(int i=size-1; i>=r; i--) A[i+1] = A[i]; A[r] = e; size++; } public E remove(int r) throwsIndexOutOfBoundsException { checkIndex(r, size()); E temp = A[r]; for(int i=r; i<size-1; i++) // shift elements down A[i] = A[i+1]; size--; returntemp; }
Skip list • lepší ako red-black tree alebo hash tabluľky • find, insert aj delete sú priemerne O(log n) • insert je stabilný, t.j. zachováva pôvodné usporiadanie rôvnakých kľúčov • in-place algoritmus – žiadna extra pamäť
SkipList node public class SkipNode { public int nodeHeight; public int key; public SkipNode[] Nodes; public SkipNode(int value,int h) { nodeHeight = h; key = value; Nodes = new SkipNode[h+1]; for (int i = 1; i <= h; i++) Nodes[i] = null; } public static final int MaxNodeValue = 65536; public static final int MinNodeValue = 0; }
SkipList find public int find(int key) { SkipNode tmp = head; for (int h = curHeight; h >= 1; h-- ) { while ( tmp.Nodes[h].key < key ) tmp = tmp.Nodes[h]; update[h] = tmp; if (tmp.Nodes[h].key == key) return key; } return SkipNode.MinNodeValue - 1; }
SkipList Insert public boolean insert(int k) { int level = 0; SkipNode[] update = new SkipNode[maxHeight+1]; …….// find k… if (tmp.Nodes[1].key == k ) return false; // duplicate key else { for(level = 1; (Math.random() < 0.5) && (level < maxHeight); level++) ; level = newLevel(); if ( level > curHeight ) { for ( int i = curHeight + 1; i <= level; i++ ) update[i] = head; curHeight = level; } } tmp = new SkipNode(k,level); for ( int i = 1; i <= level; i++ ) { tmp.Nodes[i] = update[i].Nodes[i]; update[i].Nodes[i] = tmp; } return true; }
Stromy AVL Tree (1962)B-Tree (Bayer,1971)2-3Red-Black (Sedgewick,1978)Splay Tree (Tarjan,1986)Tree-Forest
AVL Node class AVLNode { int x; AVLNode left, right; public AVLNode (int init) { x = init; left = null; right = null; } public int height () { int l = (left != null)?(left.height () + 1):0; int r = (right != null)?(right.height () + 1):0; return (l > r)?l:r; }
AVL Tree public AVLNode insert (int k) { if (k < x) if (left == null) left = new AVLNode (k); else left = left.insert (k); else if (right == null) right = new AVLNode (k); else right = right.insert (k); … pokračuje public int balance () { int l = (left != null)?(left.height () + 1):0; int r = (right != null)?(right.height () + 1):0; return (r - l); }
Rotate public AVLNode rotateLeft() { AVLNode tmp = right; right = tmp.left; tmp.left = this; return tmp; } public AVLNode rotateRight() { AVLNode tmp = left; left = tmp.right; tmp.right = this; return tmp; }
Balancing public AVLNode insert (int k) { if (k < x) ... pokračovanie... if (balance () < -1) { if (k < left.x) return rotateRight (); else { left = left.rotateLeft (); return rotateRight (); } } else if (balance () > 1) { if (k > right.x) return rotateLeft (); else { right = right.rotateRight (); return rotateLeft(); } } return this;
Splay Trees • Ak je spracovávaný uzol key, aplikuje sa metóda splay(key), • Ak strom obsahuje key, splay(key) spôsobí, že vybuble do koreňa, • Inak, koreň je najväčší kľúč < key alebo najmenší > key, • Bublaním sa key približuje do koreňa transformáciami: • Zig-Zag, • Zig-Zig • Zig
Splay find/insert public void insert(int key) { if (root == null) { root = new BinaryNode(key); return; } splay(key); if (key == root.key) return; // not found BinaryNode n = new BinaryNode(key); if (key < root.key) { n.left = root.left; n.right = root; root.left = null; } else { n.right = root.right; n.left = root; root.right = null; } root = n; } public int find(int key) { if (root == null) return -1; splay(key); if(root.key != key) return -1; return root.key; }
L T T R L R TL TR TL TR Top-down private void moveToRoot(int key) { BinaryNode l, r, t; l = r = header; t = root; header.left = header.right = null; for (;;) { if (key < t.key) { if (t.left == null) break; r.left = t; /* link right */ r = t; t = t.left; } else if (key > t.key) { if (t.right == null) break; l.right = t; /* link left */ l = t; t = t.right; } else break; } l.right = t.left; /* assemble */ r.left = t.right; t.left = header.right; t.right = header.left; root = t; }
Zig X L R L R Y X Y XR YL Yr XR YL Yr
Zig-Zig L X R L R Z Y XR Y X Z ZL Zr YR YR XR ZL Zr
Zig-Zag L X R L R Y Y XR X YL YL Z XR Z ZL Zr ZL Zr
Assembling L X X R L R XL XR XL XR
splay private void splay(int key) { BinaryNode l, r, t, y; l = r = header; t = root; header.left = header.right = null; for (;;) { if (key < t.key) { if (t.left == null) break; if (key < t.left.key) { y = t.left; /* rotate right */ t.left = y.right; y.right = t; t = y; if (t.left == null) break; } r.left = t; /* link right */ r = t; t = t.left; } else if (key > t.key) { .. . . . } else { break; } } l.right = t.left; /* assemble */ r.left = t.right; t.left = header.right; t.right = header.left; root = t; } http://www.ibr.cs.tu-bs.de/courses/ss98/audii/applets/BST/SplayTree-Example.html http://webpages.ull.es/users/jriera/Docencia/AVL/AVL%20tree%20applet.htm http://www.cs.princeton.edu/courses/archive/spr06/cos423/Handouts/self%20adjusting.pdf
Tree/Forest import java.util.*; public class Forest<E> { private List<Tree<E>> broths; public Forest(List<Tree<E>> broths) { this.broths = broths; } public String toString(){ String s = ""; char ch = '['; for(Tree<E> e:broths) { s += ch + e.toString(); ch = ','; } s += "]"; return s; } public boolean find(E key) { for(Tree<E> e:broths) { if (e.find(key)) return true; } return false; }
Tree/Forest public class Tree<E> { private E elem; private Forest<E> sons; public Tree(E elem) { this(elem,null); } public Tree(E elem, Forest<E> sons) { this.elem = elem; this.sons = sons; } public String toString() { if (sons == null) return elem.toString(); else return "("+elem.toString()+":"+sons.toString()+")"; } public boolean find(E key) { if (elem.equals(key)) return true; else if (sons != null) return sons.find(key); else return false; } }
Tree/Forest Tree<String> t1 = new Tree<String>(“system"); Tree<String> t2 = new Tree<String>("system32"); Tree<String> t3 = new Tree<String>("config"); Tree<String> t123 = new Tree<String>("WINNT", new Forest<String>(Arrays.asList(t1,t2,t3))); Tree<String> u1 = new Tree<String>("Universal crack"); Tree<String> u2 = new Tree<String>("java"); Tree<String> u12 = new Tree<String>("Program Files", new Forest<String>(Arrays.asList(u1,u2))); Forest<String> disk = new Forest<String>(Arrays.asList(t123,u12)); System.out.println(disk); System.out.println(disk.find("java")); System.out.println(disk.find("kava")); [(WINNT:[system,system32,config]),(Program Files:[Universal crack,java])] true false
Position List - interface publicinterfacePosition<E> { E element(); } public interface PositionList<E> { public intsize(); public booleanisEmpty(); public Position<E> first(); public Position<E> last(); public Position<E> next(Position<E> p) throwsInvalidPositionException, BoundaryViolationException; public Position<E> prev(Position<E> p) throwsInvalidPositionException, BoundaryViolationException; public voidaddFirst(E e); public voidaddLast(E e); public voidaddAfter(Position<E> p, E e) throwsInvalidPositionException, BoundaryViolationException; public voidaddBefore(Position<E> p, E e) throwsInvalidPositionException, BoundaryViolationException; public E remove(Position<E> p) throwsInvalidPositionException; public E set(Position<E> p, E e) throwsInvalidPositionException; }
Position List - DNode publicclassDNode<E> implementsPosition<E> { private DNode<E> prev, next; private E element; public DNode(DNode<E> newPrev, DNode<E> newNext, E elem) { prev = newPrev; next = newNext; element = elem; } public E element() throwsInvalidPositionException { if((prev == null) &&(next == null)) thrownewInvalidPositionException("Position is not in a list!"); returnelement; } public DNode<E> getNext() { returnnext; } public DNode<E> getPrev() { returnprev; } public voidsetNext(DNode<E> newNext) { next = newNext; } public voidsetPrev(DNode<E> newPrev) { prev = newPrev; } public voidsetElement(E newElement) { element = newElement; } }
Position List – implementácia 1 publicclassNodePositionList<E> implementsPositionList<E> { protected int numElts; protected DNode<E> header, trailer; public NodePositionList() { numElts = 0; header = newDNode<E>(null, null, null); trailer = newDNode<E>(header, null, null); header.setNext(trailer); } protected DNode<E> checkPosition(Position<E> p) throwsInvalidPositionException { if(p == null) thrownew InvalidPositionException("Null position passed to NodeList"); if(p == header) thrownew InvalidPositionException("The header node is not a valid position"); if(p == trailer) thrownew InvalidPositionException("The trailer node is not a valid position"); try { DNode<E> temp =(DNode<E>) p; if((temp.getPrev() == null) ||(temp.getNext() == null)) thrownew InvalidPositionException("Position not belong to a valid NodeList"); returntemp; } catch(ClassCastException e) { thrownew InvalidPositionException("Position is of wrong type for this list"); } }
Position List – implementácia 2 public Position<E> first() throwsEmptyListException { if(isEmpty()) thrownewEmptyListException("List is empty"); returnheader.getNext(); } public Position<E> prev(Position<E> p) throwsInvalidPositionException, BoundaryViolationException { DNode<E> v = checkPosition(p); DNode<E> prev = v.getPrev(); if(prev == header) thrownew BoundaryViolationException("Cannot advance past the beginning oflist"); returnprev; } public voidaddBefore(Position<E> p, E element) throwsInvalidPositionException { DNode<E> v = checkPosition(p); numElts++; DNode<E> newNode = newDNode<E>(v.getPrev(), v, element); v.getPrev().setNext(newNode); v.setPrev(newNode); } public voidaddFirst(E element) { numElts++; DNode<E> newNode = newDNode<E>(header, header.getNext(), element); header.getNext().setPrev(newNode); header.setNext(newNode); }
Position List – implementácia 3 public E remove(Position<E> p) throwsInvalidPositionException { DNode<E> v = checkPosition(p); numElts--; DNode<E> vPrev = v.getPrev(); DNode<E> vNext = v.getNext(); vPrev.setNext(vNext); vNext.setPrev(vPrev); E vElem = v.element(); // unlink the position from the list and make it invalid v.setNext(null); v.setPrev(null); returnvElem; } public E set(Position<E> p, E element) throwsInvalidPositionException { DNode<E> v = checkPosition(p); E oldElt = v.element(); v.setElement(element); returnoldElt; }