2.9K views

Uploaded by brodskye

save

- TreeTraversal
- A6-R3
- Binary Tree
- Assignment3-110001127 (1)
- Binary fghgTree Operations
- Trees
- ConsolidatedTreesProgs
- VSEM
- c Interview
- Trees Data structures
- Majority Element
- rgpv syllabus it111 data structure-i.pdf
- Lecture 7 data structures
- Trees
- Week16 Trees
- Data Structure Feb18
- Meljun Cortes Data Structures Trees
- Tree
- ADVANCED DATA STRUCTURES
- Data Structures With C June 2010
- bst
- Binary Tree
- 1 (1)
- CS 1151 Data Structures
- CSCA48_TT2_2012W
- Binary Tree Overview
- DAA Unit - II
- Data Structres Final Fall
- bcsl-033
- Libro7
- Assembly - IntelCodeTable
- fasc4b
- Flood Fill
- Optimal BSTmeets OOP
- fasc3b
- SQL Server Reference
- Rebalancing BST
- Majority Element
- fasc4a
- fasc0a
- Handshakes
- fasc3a
- fasc0c
- fasc1a
- fasc2a
- fasc1
- fasc0b
- fasc2b
- Beam Forming Algorithm Implementation Using FPGA
- Scientific python (by Stanford)
- b.tech Matlab Mini Project List
- 2
- unit 3 review answers
- Implicit Runge-Kutta schemes for optimal control problems with evolution equations
- SVM_hype or Hallelujah
- Classification Rule Construction Using Particle Swarm Optimization Algorithm for Breast Cancer Data Sets
- Communication Signal Processing PDF
- Frontespizio.pdf
- 01. Introduction to Datastructure 2
- DSP Assignment 1 Ashwin
- 06 Hashing Chaining
- algotest.docx
- Syllabus - METODOS NUMERICOS - UNMSM - FIEE
- DESIGN OF A DIGITAL FRONT-END TRANSMITTER FOR OFDM-WLAN SYSTEMS USING FPGA
- 1metodosjoathan
- Solution Smith Rule
- Matematicas Discretas Camino mas corto y a la Ancho
- 2-Fundamentals on ADCs-Part 1
- The frequency domain_part2.ppt
- 3613-s05
- Course Hero Final Exam Soluts.[1]
- Pedro Godoy Control7 Análisis de Algoritmos IACC 2018
- Laboratorio Ieee Señales y Sistemas Laboratorio 5 1.1
- MIT2_29S15_Lecture10
- ee608_hw2
- 31 Huffman Encoding
- Transdormada de Fouerier
- Manual Wavelet

You are on page 1of 6

We introduce a data structure called the rank tree to solve the Josephus problem efficiently.

n players, numbered 1 to n, are sitting in a circle; starting at player 1, a hot potato is passed; after m passes,

the player holding the hop potato is eliminated, the circle closes ranks, and the game continued with the

player who was sitting after the eliminated player picking up the hot potato; the last remaining player wins.

The Josephus problem arose in the first century A.D in a cave on a mountain in Israel where Jewish zealots

were being besieged Roman soldiers. The historian Josephus was among them. To Josephus’s consternation,

the zealots voted to enter into a suicide pact rather than surrender to the Romans. He suggested the game

that now bears his name. The hot potato was sentence of death to the person next to the one who got the

potato. Josephus rigged to get the last lot and convinced the remaining intended victim that the two of

them should surrender. That is how we know about this game; in effect, Josephus cheated.

Fig. 1 is an example with 5 players and the number of passes being 1.

1 1 1

5 2 5 5 5

4 3 4 3 3 3 3

Figure 1: The Josephus problem: At each step, the darkest circle represents the initial holder and the

lightly shaded circle represents the player who received the hot potato (and is eliminated). Passes are made

clockwise.

What data structure to use? We need a data structure to store the circle of player with following methods:

• Pass the potato to the next person.

• Delete the person holding the potato.

Using a Linked List. The required methods suggest that we can represent the players in a linked list,

actually in a circular linked list which is even better considering that players are sitting in a circle. Even

though Java does not provide one, we can simulate it easily. If you see the following code,

// Return the winner in the Josephus problem.

// Linked list implementation.

public static int josephus(int people, int passes)

{

List<Integer> list = new LinkedList<Integer>();

for (int i = 1; i <= people; i++)

list.add(i);

Iterator<Integer> itr = list.iterator();

while (people > 1) {

for (int i = 0; i <= passes; i++) {

1. if (!itr.hasNext())

2. itr = list.iterator();

1

itr.next();

}

itr.remove();

--people;

}

// find out who the winner is

itr = list.iterator();

return itr.next( );

}

you simply notice that adding the line number 1 and 2 only makes the circular linked list simulation possible.

How much time takes to solve the Josephus problem with a linked list? It takes O(m + 1) for the hot

potato to reach to the right player who will be eliminated. Since we continue to eliminate players until only

one player is left, O(n − 1) rounds are needed. Multiplying them, we get O(mn), which means quadratic

time. Can we do better? What about using an array list?

Using an Array List. To use an array list, first observe that if the potato is currently at position p, then

after m passes, it will be at position (p + m)%n. (Here, positions are numbered from 0 to n − 1.) Then we

can easily find the player who will be eliminated in O(1). But how much does it take to remove the player

at the position? Remember that after removing the player, we need to compact the array, which means we

have to shift O(n − p − 1) elements behind the removed one. Multiplying this with O(n − 1) rounds, we get

O(n2 ). Still quadratic time takes to solve our problem.

A linked list is good at deleting an object, but not very good at finding it; An array list is good at finding

an object, but not very good at removing it; somehow we need a data structure which good at both finding

and deleing an object.

Here, we introduce the rank tree which supports the following operations.

2. find(int k) returns the item at rank (index) k;

4. size() returns the current size;

Idea.

• Store the elements in a binary tree in in-order sequence. Store in each node t the size of the subtree

whose root is t.

• To find the node with rank k, we just have to follow the path from the root.

• To remove the node with rank k, there are three cases.

– if t has zero or one subtree, just remove t and change a reference of its parent.

– if t has two subtrees, delete the leftmost node in its right subtree instead, and move the element

stored there to t. (rename it)

Of course we have to recompute the size of nodes after deleting a node t.

Let us look at implementations of above method with examples.

2

A Node. An element of the binary tree.

private static class Node<AnyType> {

AnyType iElement;

Node<AnyType> iLeft;

Node<AnyType> iRight;

int iSize;

iElement = element;

iLeft = iRight = null;

iSize = 1;

}

public void recomputeSize() {

int leftSize = (iLeft != null) ? iLeft.iSize : 0;

int rightSize = (iRight != null) ? iRight.iSize : 0;

iSize = leftSize + 1 + rightSize;

}

}

// Construct the tree.

public RankTree(AnyType [] elements) {

iRoot = buildTree(elements, 0, elements.length - 1);

}

// Internal method to build tree for elements from i to j.

private Node<AnyType> buildTree(AnyType [] elements, int i, int j)

{

if (j < i) return null;

if (i == j) return new Node<AnyType>(elements[i]);

int mid = (i + j) / 2;

Node<AnyType> t = new Node<AnyType>(elements[mid]);

t.iLeft = buildTree(elements, i, mid - 1);

t.iRight = buildTree(elements, mid + 1, j);

t.recomputeSize();

return t;

}

A Find Method: Let us assume that we want to find a node t with rank k and also let us denote the

number of elements in the left subtree of the current node as s. Then, there are the following three cases:

• if k = s, return the current node.

• if k > s, go to the right subtree, change the rank into k − (s + 1) instead of k, and apply it again.

As you can see, in all the cases, you only need to follow a path from the root.

// returns null if not found.

public AnyType find(int k) {

3

6

12

3 9

5 6

1 4 7 11

2 2 2 3

2 5 8 10 12

1 1 1 1 1

Figure 2: Construction of the rank tree with 12 elements and with the size of each node written in red.

}

// Internal method to find node at rank k in a subtree rooted at t.

// returns node containing the matched item.

private Node<AnyType> find(int k, Node<AnyType> t) {

if (t == null) throw new IllegalArgumentException();

int leftSize = (t.iLeft != null) ? t.iLeft.iSize : 0;

if (k < leftSize) return find(k, t.iLeft);

if (k == leftSize) return t;

return find(k - leftSize - 1, t.iRight);

}

9>5

6

12

3 9 9 − (5 + 1) = 3 > 2

5 6

1 4 7 11 3 − (2 + 1) = 0 < 1

2 2 2 3

2 5 8 10 12

1 1 1 1 1

Figure 3: Find(rank 9): The darkest nodes are visited to find it and lightly shaded nodes are referenced

nodes to know the number of elements in the left subtrees.

A Delete Method.

// Remove element at rank k from the tree..

public void remove(int k) {

4

iRoot = remove(k, iRoot);

}

// Internal method to remove node at rank k from a subtree rooted at t.

// returns the new root.

private Node<AnyType> remove(int k, Node<AnyType> t) {

if (t == null) throw new IllegalArgumentException();

int leftSize = (t.iLeft != null) ? t.iLeft.iSize : 0;

if (k < leftSize) t.iLeft = remove(k, t.iLeft);

else if (k > leftSize) t.iRight = remove(k - leftSize - 1, t.iRight);

else {

// need to remove node t

if (t.iLeft != null && t.iRight != null) { // Two children

t.iElement = findFirst(t.iRight).iElement;

t.iRight = removeFirst(t.iRight);

}

else t = (t.iLeft != null) ? t.iLeft : t.iRight;

}

if (t != null) t.recomputeSize();

return t;

}

6 6 6

11 10 9

3 9 3 9 3 10

5 5 4 5 4 4

1 4 7 11 1 7 11 1 7 11

2 2 1 3 2 1 3 2 1 2

2 5 10 12 2 5 10 12 2 5 12

1 1 1 1 1 1 1 1 1 1 1

(a) After deleting the node with rank 7 (b) After deleting the node with rank 3 (c) After deleting the node with rank 6

As you can see, there are a lot of recursion going on. Do you know why this is so? It is because using

recursion, we can remember the path from the root. If you notice that a node of a tree has only outgoing

edges to its children, not its parent, you may wonder how we can possibly go upward directly to answer

questions like recomputing the size of each root. Here, we do not need to go upward explicitly. Instead,

recursion tells you where you stayed and computes the value where you stayed. That is the beauty of

recursion. :-)

Analysis.

1. find(int k): O(h)

2. remove(int k): O(h)

3. size(): O(1)

where h is the height of the tree. Recall from the last class, that the height is the length of the longest

path from the root. Since we can make a perfectly balanced tree in the construction step and by not having

an insertion operator, the balance is never broken, we know that the height of the rank tree is dlog(n + 1)e−1.

5

Therefore find and remove take time O(log n), and the total running time for the Josephus problem is

O(n log n).

The running time of the RankTree constructor, by the way, is O(n). This follows from solving the

recursive formula T (n) = 2T (n/2) + O(1).

- TreeTraversalUploaded byandi arfian
- A6-R3Uploaded byShiv Pathak
- Binary TreeUploaded bySahil Joshi
- Assignment3-110001127 (1)Uploaded byHrithika Reddy
- Binary fghgTree OperationsUploaded byKaja Najeemudin
- TreesUploaded byShashwat Jha
- ConsolidatedTreesProgsUploaded byPreeti Rawat
- VSEMUploaded byKaushal Pandey
- c InterviewUploaded bytribhuwanPrakash
- Trees Data structuresUploaded bySiddharthaSid
- Majority ElementUploaded bybrodskye
- rgpv syllabus it111 data structure-i.pdfUploaded bysatti2628
- Lecture 7 data structuresUploaded bySakura2709
- TreesUploaded bybayentapas
- Week16 TreesUploaded byDylan Gray
- Data Structure Feb18Uploaded bynisha sharma
- Meljun Cortes Data Structures TreesUploaded byMELJUN CORTES, MBA,MPA
- TreeUploaded byBodhisatwa Chowdhury
- ADVANCED DATA STRUCTURESUploaded byvenkatesh
- Data Structures With C June 2010Uploaded byPrasad C M
- bstUploaded byAnshu Kumar
- Binary TreeUploaded byHolly Anderson
- 1 (1)Uploaded bySuresh Babu
- CS 1151 Data StructuresUploaded byanon-845033
- CSCA48_TT2_2012WUploaded byexamkiller
- Binary Tree OverviewUploaded byDebnath JM
- DAA Unit - IIUploaded bySubathra Devi Mourougane
- Data Structres Final FallUploaded byCrow Tome
- bcsl-033Uploaded bypujan bajracharya
- Libro7Uploaded byMike Gálvez

- Assembly - IntelCodeTableUploaded bybrodskye
- fasc4bUploaded bybrodskye
- Flood FillUploaded bybrodskye
- Optimal BSTmeets OOPUploaded bybrodskye
- fasc3bUploaded bybrodskye
- SQL Server ReferenceUploaded bybrodskye
- Rebalancing BSTUploaded bybrodskye
- Majority ElementUploaded bybrodskye
- fasc4aUploaded bybrodskye
- fasc0aUploaded bybrodskye
- HandshakesUploaded bybrodskye
- fasc3aUploaded bybrodskye
- fasc0cUploaded bybrodskye
- fasc1aUploaded bybrodskye
- fasc2aUploaded bybrodskye
- fasc1Uploaded bybrodskye
- fasc0bUploaded bybrodskye
- fasc2bUploaded bybrodskye

- Beam Forming Algorithm Implementation Using FPGAUploaded byphithuc
- Scientific python (by Stanford)Uploaded bynamcoltech
- b.tech Matlab Mini Project ListUploaded byRasool Reddy
- 2Uploaded byvvvv4
- unit 3 review answersUploaded byroberttolar
- Implicit Runge-Kutta schemes for optimal control problems with evolution equationsUploaded byjojo
- SVM_hype or HallelujahUploaded byVaibhav Jain
- Classification Rule Construction Using Particle Swarm Optimization Algorithm for Breast Cancer Data SetsUploaded bySundaravada
- Communication Signal Processing PDFUploaded byTammy
- Frontespizio.pdfUploaded byLoredana Magda
- 01. Introduction to Datastructure 2Uploaded byfaisal
- DSP Assignment 1 AshwinUploaded byAkshaySudhir
- 06 Hashing ChainingUploaded byAbhishek Kumar
- algotest.docxUploaded byAditya Mishra
- Syllabus - METODOS NUMERICOS - UNMSM - FIEEUploaded byJuan Colonio Muñoz
- DESIGN OF A DIGITAL FRONT-END TRANSMITTER FOR OFDM-WLAN SYSTEMS USING FPGAUploaded byMd.Maruf Ahamed Beddut
- 1metodosjoathanUploaded byAc Aryan
- Solution Smith RuleUploaded byThu Ha Nguyen
- Matematicas Discretas Camino mas corto y a la AnchoUploaded byOmar Bustamante
- 2-Fundamentals on ADCs-Part 1Uploaded byNaveen Kumar
- The frequency domain_part2.pptUploaded byRyan Wong
- 3613-s05Uploaded byoscura
- Course Hero Final Exam Soluts.[1]Uploaded byChristopher Haynes
- Pedro Godoy Control7 Análisis de Algoritmos IACC 2018Uploaded bypedro
- Laboratorio Ieee Señales y Sistemas Laboratorio 5 1.1Uploaded byjonnyzsx
- MIT2_29S15_Lecture10Uploaded byIhab Omar
- ee608_hw2Uploaded byMahesh More
- 31 Huffman EncodingUploaded byPlasma EA
- Transdormada de FouerierUploaded byAmando Acosta
- Manual WaveletUploaded byjulio gamboa