From 79b9a63be8633a85088fb1ee0a1316239732b2c5 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Tue, 7 Jul 2015 20:28:16 +0300 Subject: [PATCH 01/11] add solution --- .../ClosestCoffeeStore.java | 114 +++++++++++++++++- week4/3-Phone-Numbers/PhoneNumbers.java | 104 ++++++++++++++++ 2 files changed, 213 insertions(+), 5 deletions(-) create mode 100644 week4/3-Phone-Numbers/PhoneNumbers.java diff --git a/week4/1-Closest-Coffee-Store/ClosestCoffeeStore.java b/week4/1-Closest-Coffee-Store/ClosestCoffeeStore.java index 7cd512b..d880cbd 100644 --- a/week4/1-Closest-Coffee-Store/ClosestCoffeeStore.java +++ b/week4/1-Closest-Coffee-Store/ClosestCoffeeStore.java @@ -1,7 +1,111 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ public class ClosestCoffeeStore { + private boolean[] visited; + Queue q ; + public ClosestCoffeeStore(){ + + } + // Finds the closest coffee store to a point. + public int closestCoffeeStore(boolean[][] graph, boolean[] isCoffeStore, int startingPoint) { + // ... + q=new LinkedList(); + visited=new boolean[isCoffeStore.length]; + // closestCoffeeStore(graph, isCoffeStore, startingPoint); + + int current=startingPoint; + if(isCoffeStore[current]==true){ + return current; + } + + q.add(current); + while(!q.isEmpty()){ + int peek = q.peek(); + if(isCoffeStore[peek] == true){ + return peek; // exit success + } + visited[peek]=true; + traverseChildren(peek, graph,isCoffeStore); + q.poll(); + } + + + return -1; + } + public void traverseChildren(int index , boolean[][] graph , boolean[] isCoffeStore){ + for(int i =0 ;i < graph[index].length;i++){ + + if( graph[index][i] == true && visited[i] == false){ + q.add(i); + visited[i]=true; + } + + } + } + /* public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } - // Finds the closest coffee store to a point. - public int closestCoffeeStore(bool[][] graph, boolean[] isCoffeStore, int startingPoint) { - // ... - } -} + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + ClosestCoffeeStore c = new ClosestCoffeeStore(); + int n; + int startingPoint; + n=sc.nextInt(); + + int[][] graph = new int[n][n]; + boolean[] isCoffeeStore = new boolean[n]; + } + */ +} \ No newline at end of file diff --git a/week4/3-Phone-Numbers/PhoneNumbers.java b/week4/3-Phone-Numbers/PhoneNumbers.java new file mode 100644 index 0000000..54d8bbb --- /dev/null +++ b/week4/3-Phone-Numbers/PhoneNumbers.java @@ -0,0 +1,104 @@ + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; +import java.util.TreeMap; + + +/** + * + * @author qvka + */ +public class PhoneNumbers { + + // private TreeMap map; + class Graph{ + private Queue q; + private boolean[] visited; + public Graph(int size){ + q=new LinkedList<>(); + visited= new boolean[size]; + } + + public int go(int[][] graph , int pos){ + q.add(pos); + int counter=0; + int temp; + for(int index = 0 ; index < graph.length ; index++){ + if(visited[index] == true){ + continue; + } + while(!q.isEmpty()){ + temp = q.poll(); + visited[temp]= true; + visitChildren(graph, temp); + counter++; + } + } + return counter; + } + + public void visitChildren(int[][] graph, int pos){ + for(int col = 0; col < graph[pos].length ; col++){ + if( visited[col] == false && graph[pos][col] == 1){ + q.add(col); + visited[col]=true; + } + + + } + } + } + + + + public void getNumbers(){ + Scanner sc = new Scanner(System.in); + TreeMap tree = new TreeMap(); + int numberOfPpl; + int phoneNum; + numberOfPpl = sc.nextInt(); + // map of phone numbers and corespondng indexes + for(int i = 0 ; i < numberOfPpl ; i++){ + phoneNum = sc.nextInt(); + tree.put(phoneNum, i); + } + int temp; + // adding graph values + int[][] graph = new int[numberOfPpl][numberOfPpl]; + for(int i = 0 ; i < numberOfPpl ; i++){ + temp = sc.nextInt(); + for(int y = 0 ; y < temp; y++){ + int index = tree.get(sc.nextInt()); + graph[i][index]=1; + graph[index][i]=1; + } + } + + //print graph + for(int row = 0 ; row < numberOfPpl ; row++){ + for(int col = 0 ; col < numberOfPpl ; col++){ + System.out.print(graph[row][col]+" "); + } + System.out.println(""); + } + Graph gr = new Graph(numberOfPpl); + int result= gr.go(graph, 0); + System.out.println(result); + // for(int i = 0 ; i < n-1 ; i++){ + + // } + + // System.out.println(tree.root.left.element.value); + } + public static void main(String[] args) { + PhoneNumbers p = new PhoneNumbers(); + p.getNumbers(); + + + + + + } + +} From 77638201baf6d1ac24917906e4461d068f77f89e Mon Sep 17 00:00:00 2001 From: qvkaa Date: Thu, 30 Jul 2015 20:30:37 +0300 Subject: [PATCH 02/11] add solutions --- week2/1-Roots/Roots.java | 23 +- week2/2-Birthday-Ranges/BirthdayRanges.java | 113 +++++++- week2/3-Quadruplets/Quadruplets.java | 116 +++++++- week2/4-Phone-Book/PhoneBook.java | 69 ++++- week2/5-Heap-Sort/HeapSort.java | 193 ++++++++++++- week2/6-K-Lists/KLists.java | 249 ++++++++++++++++- week2/7-K-Min/KMin.java | 203 +++++++++++++- week3/1-BST/BST.java | 104 ++++++- week3/2-Min-Max-Heap/MinMaxHeap.java | 112 +++++++- week3/3-Online-Median/Median.java | 253 +++++++++++++++++- week3/4-Phone-Book-2/PhoneBook.java | 126 +++++++-- .../5-Bandwidth-Manager/BandwidthManager.java | 249 ++++++++++++++++- week3/6-Birthday-Ranges-2/BirthdayRanges.java | 236 ++++++++++++++-- week3/7-Range-Minimum-Query/RMQ.java | 205 +++++++++++++- .../8-Jumping-Soldiers/Jumping Soldiers.java | 96 +++++++ 15 files changed, 2211 insertions(+), 136 deletions(-) create mode 100644 week3/8-Jumping-Soldiers/Jumping Soldiers.java diff --git a/week2/1-Roots/Roots.java b/week2/1-Roots/Roots.java index 53ce7b4..841c46f 100644 --- a/week2/1-Roots/Roots.java +++ b/week2/1-Roots/Roots.java @@ -1,7 +1,24 @@ public class Roots { // Finds the square root of a number using binary search. - public double squareRoot(int number) { - // ... - } + public static double findRoot(int n){ + double left = 1; + double right = n; + double mid = left + (right-left)/2; + int counter=0; + while (Math.abs((mid * mid) - n) > 0.000001) { + mid = left + ( right - left ) / 2; + if( (mid * mid) > n ){ + right=mid; + }else{ + left= mid; + } + counter++; + } + if(counter >= 68){ + System.out.println(n +" steps : " + counter); + } + return mid; + + } } diff --git a/week2/2-Birthday-Ranges/BirthdayRanges.java b/week2/2-Birthday-Ranges/BirthdayRanges.java index b946d45..6f94951 100644 --- a/week2/2-Birthday-Ranges/BirthdayRanges.java +++ b/week2/2-Birthday-Ranges/BirthdayRanges.java @@ -1,15 +1,104 @@ -import java.util.List; +import java.util.Scanner; -public class BirthdayRanges { - - public static class Pair { +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ - public int start; - public int end; - } - - // Returns a vector with the number of people born in the specific ranges. - public List birthdaysCount(List birthdays, List ranges) { - // ... - } +/** + * + * @author qvka + */ +public class BirthdayRanges { + public static int[] getRanges(int[] list, int[] from, int[] to){ + int[] birthdays = new int[366]; + int sum; + int temp; + int index; + for(int i = 0 ; i num){ + r=mid-1; + }else if(a[mid] < num){ + l=mid+1; + }else{ + return mid; + } + } + return -1; + } + public static int get(int[] a, int[] b,int[] c,int[] d){ + int index=0; + int temp; + int firstIndex,lastIndex,range,midIndex; + int counter=0; + int[] store = new int[a.length*b.length]; + for(int a1=0; a1 0 && (store[firstIndex] == store[firstIndex-1])){ + firstIndex=binarySearch(store, -temp, 0, firstIndex-1); + + } + lastIndex=midIndex; + //we do the same check but for the right + + while(lastIndex < store.length-1 && (store[lastIndex] == store[lastIndex+1]) ){ + lastIndex=binarySearch(store, -temp, lastIndex+1, store.length-1); + } + + range = (lastIndex-firstIndex) +1; + + counter+= range; + + } + } + + return counter; + } + public static class MyScanner{ + BufferedReader br; + StringTokenizer st; + public MyScanner(){ + br = new BufferedReader(new InputStreamReader(System.in)); + } + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + int nextInt() { + return Integer.parseInt(next()); + } + } + + public static void main(String[] args) { + MyScanner sc= new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int n; + n=sc.nextInt(); + int[][] matrix=new int[4][n]; + for(int i = 0 ; i< 4 ; i++){ + for(int y=0 ; y < n ; y++){ + matrix[i][y]=sc.nextInt(); + } + } + + out.println(get(matrix[0], matrix[1], matrix[2], matrix[3])); + + } + +} \ No newline at end of file diff --git a/week2/4-Phone-Book/PhoneBook.java b/week2/4-Phone-Book/PhoneBook.java index f1e202c..308d62b 100644 --- a/week2/4-Phone-Book/PhoneBook.java +++ b/week2/4-Phone-Book/PhoneBook.java @@ -1,13 +1,58 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; +import java.util.TreeMap; +/** + * + * @author qvka + */ public class PhoneBook { - - public static class Contact { - - public String name; - public int number; - } - - // Find the names of people based on their phone numbers. - public List lookupNames(List phoneBook, List numbers) { - // ... - } -} + + // only testing time difference + // not original solution + public static class MyScanner{ + BufferedReader br; + StringTokenizer st; + public MyScanner(){ + br = new BufferedReader(new InputStreamReader(System.in)); + } + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + int nextInt() { + return Integer.parseInt(next()); + } + } + + public static void main(String[] args) { + PhoneBook p = new PhoneBook(); + TreeMap map = new TreeMap(); + int n,m; + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + n= sc.nextInt(); + m= sc.nextInt(); + StringBuilder sb = new StringBuilder(); + for(int i = 0 ; i < n ; ++i){ + map.put(sc.nextInt(),sc.next()); + } + + for(int i = 0 ; i < m ; ++i){ + sb.append(map.get(sc.nextInt())).append("\n"); + } + int last= sb.length(); + sb.delete(last-1 , last); + out.println(sb.toString()); + } + +} \ No newline at end of file diff --git a/week2/5-Heap-Sort/HeapSort.java b/week2/5-Heap-Sort/HeapSort.java index 3345274..39626ca 100644 --- a/week2/5-Heap-Sort/HeapSort.java +++ b/week2/5-Heap-Sort/HeapSort.java @@ -1,7 +1,190 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; + + public class HeapSort { + public static class MyScanner{ + BufferedReader br; + StringTokenizer st; + public MyScanner(){ + br = new BufferedReader(new InputStreamReader(System.in)); + } + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + int nextInt() { + return Integer.parseInt(next()); + } + } + + public class Heap{ + private int[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[cap]; + } + public Heap(int[] array,boolean isMin){ + this.isMinHeap=isMin; + size= array.length; + heap = new int[size+1]; + System.arraycopy(array, 0, heap, 1, size); + buildHeap(); + } + public int size(){ + return this.size; + } + private void expandHeap(){ + int[] old = heap; + heap = new int[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(int value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value < heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value > heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + heap[position] = value; + } + public int deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + int top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public int peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + + // returns heap top and places k at the top and traverses down + public int swap(int k){ + int temp = heap[1]; + heap[1]=k; + movingDown(1); + return temp; + } + public void movingDown(int k){ + int temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child] > heap[child+1] ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child] < heap[child+1] ){ // take greater child + child++; + } + } + } + if( isMinHeap ){ //min heap + if( temp > heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp < heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + } + k = child; + } + heap[k]=temp; + } + public void heapSort(){ + int temp = size; + while(size > 1){ + heap[size]= swap(heap[size]); + size--; + } + size = temp; + } + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k]+" "; + return out; + } + public String toString(boolean heapSorted){ + StringBuilder sb = new StringBuilder(); + for(int i = size ; i >= 1 ; --i ){ + sb.append(heap[i]).append(" "); + } + return sb.toString(); + } + + } + + public String go(int[] sequence){ + Heap hp = new Heap(sequence,true); + hp.heapSort(); + return hp.toString(true); + } - // Sorts a sequence of integers. - public void sort(int[] sequence) { - // ... - } -} + + public static void main(String[] args) { + MyScanner scanner = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int[] sequence; + int n; + n = scanner.nextInt(); + sequence = new int[n]; + for(int i = 0 ; i < n ; ++i){ + sequence[i] = scanner.nextInt(); + } + + HeapSort hs = new HeapSort(); + out.println(hs.go(sequence)); + + } + +} \ No newline at end of file diff --git a/week2/6-K-Lists/KLists.java b/week2/6-K-Lists/KLists.java index f49cb83..f9cad66 100644 --- a/week2/6-K-Lists/KLists.java +++ b/week2/6-K-Lists/KLists.java @@ -1,14 +1,243 @@ -import java.util.List; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.LinkedList; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ public class KLists { + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } - public class Node { - public int value; - public Node next; - } + } + class Pair{ + int key; + int value; + public Pair(int key , int value){ + this.key=key; + this.value = value; + } + } + class Heap{ + + private Pair[] heap; // starting from 1 + private static final int CAPACITY = 150; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Pair[CAPACITY]; + } + public Heap(boolean isMin,int cap){ + this.isMinHeap = isMin; + size=0; + heap = new Pair[cap+1]; + } + public Heap(int[] array,boolean isMin){ + this.isMinHeap=isMin; + size= array.length; + heap = new Pair[size+1]; + System.arraycopy(array, 0, heap, 1, size); + buildHeap(); + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + Pair[] old = heap; + heap = new Pair[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(Pair value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; - // Merge K sorted lists. - public Node merge(List lists) { - // ... - } -} + //move up min heap max heap + /* while( position > 1 && (isMinHeap ? value < heap[position/2] : value > heap[position/2] )){ + heap[position]=heap[position/2]; + position=position/2; + } */ + //variant 2 + + if(isMinHeap){ + while( position > 1 && value.key < heap[position/2].key ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value.key > heap[position/2].key ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + + heap[position] = value; + } + public Pair deleteTop() throws RuntimeException{ + // if(size == 0){ + // throw new RuntimeException(); + // } + Pair top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public Pair peek(){ + // if(size == 0){ + // throw new RuntimeException(); + // } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + + public void movingDown(int k){ + Pair temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child].key > heap[child+1].key ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child].key < heap[child+1].key ){ // take greater child + child++; + } + } + } + + if( isMinHeap ){ //min heap + if( temp.key > heap[child].key ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp.key < heap[child].key ){ + heap[k] = heap[child]; + }else{ + break; + } + } + + k = child; + } + + heap[k]=temp; + } + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += "k="+heap[k].key +" v="+heap[k].value+" "; + return out; + } + } + + private Heap heap; + + public void merge(LinkedList[] lists){ + Heap hp = new Heap(true,lists.length); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + StringBuilder sb= new StringBuilder(); + int value1; + // we add the first element on each list ot the heap + for(int i = 0 ; i < lists.length; i++){ + + //pair ( key = integer from the list , value =index of that list in the array + if(!lists[i].isEmpty()){ + hp.insert(new Pair( lists[i].poll(), i)); + // lists[i].removeFirst(); + } + } + //pop the heap , and add new value from the same list the popped value came from + while(hp.size > 0){ + sb.append(hp.peek().key).append(" "); + value1 = hp.peek().value; // the index of the list in the array + hp.deleteTop(); + if(!lists[value1].isEmpty()){ // we take another element of the same list + hp.insert(new Pair(lists[value1].poll() , value1)); + // lists[value1].removeFirst(); + } + } + out.println(sb.toString()); + } + + public static void main(String[] args) { + KLists kl = new KLists(); + + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + LinkedList[] arr = new LinkedList[n]; + + int temp; + for(int i = 0 ; i < n ; i++){ + arr[i]=new LinkedList<>(); + while( (temp=sc.nextInt()) != -1){ + arr[i].add(temp); + } + + } + + kl.merge(arr); + + } + +} \ No newline at end of file diff --git a/week2/7-K-Min/KMin.java b/week2/7-K-Min/KMin.java index 348b3b7..abbee93 100644 --- a/week2/7-K-Min/KMin.java +++ b/week2/7-K-Min/KMin.java @@ -1,9 +1,200 @@ -import java.util.List; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author qvka + */ public class KMin { + + public static class MyScanner{ + BufferedReader br; + StringTokenizer st; + public MyScanner(){ + br = new BufferedReader(new InputStreamReader(System.in)); + } + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + } + public class Heap{ + private int[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[cap+1]; + } + public Heap(int[] array,boolean isMin){ + this.isMinHeap=isMin; + size= array.length; + heap = new int[size+1]; + System.arraycopy(array, 0, heap, 1, size); + buildHeap(); + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + int[] old = heap; + heap = new int[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(int value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value < heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value > heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + + heap[position] = value; + } + public int deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + int top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public int peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public int swap(int k){ + int temp = heap[1]; + heap[1]=k; + movingDown(1); + return temp; + } + public void movingDown(int k){ + int temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child] > heap[child+1] ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child] < heap[child+1] ){ // take greater child + child++; + } + } + } + + if( isMinHeap ){ //min heap + if( temp > heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp < heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + } + + k = child; + } - // Finds the k-th minimum element in an unsorted collection. - public int kthMinimum(List numbers, int k) { - // ... - } -} + heap[k]=temp; + } + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k]+" "; + return out; + } + } + + public int getKMin(int[] array1 ,int[] array2, int k){ + Heap heap = new Heap(array1,false); // max heap + + for(int i = 0 ; i < array2.length ; ++i){ + if( array2[i] < heap.peek() ){ + heap.swap(array2[i]); + } + } + return heap.peek(); + } + public static void main(String[] args) { + MyScanner scanner = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int[] array1; // [k] size array - easier to build heap + int[] array2; // rest of array - [n-k] size + int n,k; + n = scanner.nextInt();// lenght of vector + k = scanner.nextInt(); // k-th element we need + array1 = new int[k]; + n-=k; + // 10 4 + // + + array2 = new int[n]; + for(int i = 0 ; i < k ; ++i){ + array1[i] = scanner.nextInt(); + } + for(int i = 0; i < n; ++i){ + array2[i] = scanner.nextInt(); + } + KMin min = new KMin(); + int result = min.getKMin(array1,array2,k); + out.println(result); + } + +} \ No newline at end of file diff --git a/week3/1-BST/BST.java b/week3/1-BST/BST.java index e7ff8a1..345f9ff 100644 --- a/week3/1-BST/BST.java +++ b/week3/1-BST/BST.java @@ -1,14 +1,96 @@ -public class BST { +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; - public static class Node { +/** + * + * @author qvka + */ +public class BinarySearchTree { + private boolean isBST = true; + private int[] array; // root at 1 ; current Min at 0 + private int size; + public BinarySearchTree(int[] array){ + this.size = array.length; + this.array = new int[size+1]; + System.arraycopy(array, 0, this.array, 1, size); + this.array[0] = Integer.MIN_VALUE; // current min; + } + public boolean isBinarySearchTree(){ + inOrder(1); + return isBST; + } + public void inOrder(int k){ + //botoom + if( (!isBST) || (k > size) || (array[k] == 0) ){ + return; + } + //visit left child + inOrder(k*2); + //check if valid bst + if( array[0] > array[k]){ + isBST = false; + }else{ + array[0] = array[k]; + } + //visit right child + inOrder((k*2)+1); + } + + public static class MyScanner { + BufferedReader br; + StringTokenizer st; - public int value; - public Node left; - public Node right; - } + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } - // Checks if a binary tree is a binary search tree. - public boolean isBST(Node root) { - // ... - } -} + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args){ + MyScanner scanner = new MyScanner(); + int n = scanner.nextInt(); + int[] array = new int[n]; + for(int i = 0 ; i < n ; ++i){ + array[i] = scanner.nextInt(); + } + BinarySearchTree bst = new BinarySearchTree(array); + if(bst.isBinarySearchTree()){ + System.out.println("YES"); + }else{ + System.out.println("NO"); + } + } +} \ No newline at end of file diff --git a/week3/2-Min-Max-Heap/MinMaxHeap.java b/week3/2-Min-Max-Heap/MinMaxHeap.java index e6fad9a..c1a3c3f 100644 --- a/week3/2-Min-Max-Heap/MinMaxHeap.java +++ b/week3/2-Min-Max-Heap/MinMaxHeap.java @@ -1,14 +1,106 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author qvka + */ public class MinMaxHeap { + private boolean isMinMaxHeap; + private int[] array; + private int size; + public MinMaxHeap(int[] arr){ + isMinMaxHeap = true; + this.size = arr.length; + this.array = new int[size+1]; + System.arraycopy(arr, 0, this.array, 1, this.size); + } + public boolean isMinMaxHeap(){ + int level = 1; + int min = Integer.MIN_VALUE; + int max = Integer.MAX_VALUE; + + preOrder(1, min, max,1); + return this.isMinMaxHeap; + } + public void preOrder(int k , int min , int max , int level){ + if(k > size || array[k] == 0){ + return; + } + if( array[k] <= min || array[k] >= max ){ + isMinMaxHeap = false; + return; + } + if ( level % 2 == 1){ + min = array[k]; + }else{ + max = array[k]; + } + preOrder(k*2, min, max,level+1); + preOrder( (k*2)+1 , min , max, level+1); + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } - public static class Node { + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } - public int value; - public Node left; - public Node right; - } + int nextInt() { + return Integer.parseInt(next()); + } - // Checks if a binary tree is a min/max heap. - public boolean isMinMax(Node root) { - // ... - } -} + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args) { + MyScanner scanner = new MyScanner(); + int n = scanner.nextInt(); + int[] arr = new int[n]; // 1-based + for(int i = 0 ; i < n ; ++i){ + arr[i] = scanner.nextInt(); + } + MinMaxHeap heap = new MinMaxHeap(arr); + if(heap.isMinMaxHeap()){ + System.out.println("YES"); + }else{ + System.out.println("NO"); + } + } + +} \ No newline at end of file diff --git a/week3/3-Online-Median/Median.java b/week3/3-Online-Median/Median.java index e394e66..e694272 100644 --- a/week3/3-Online-Median/Median.java +++ b/week3/3-Online-Median/Median.java @@ -1,7 +1,250 @@ -public class Median { +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; - //inserts the number and returns the median - public int insert(int number){ +/** + * + * @author qvka + */ +public class Week3OnlineMedian { + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + + } + class Heap{ + + private int[] heap; // starting from 1 + private static final int CAPACITY = 600000; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[CAPACITY]; + } + public Heap(int[] array,boolean isMin){ + this.isMinHeap=isMin; + size= array.length; + heap = new int[size+1]; + System.arraycopy(array, 0, heap, 1, size); + buildHeap(); + } + public int size(){ + return this.size; + } + private void expandHeap(){ + int[] old = heap; + heap = new int[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(int value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + + //move up min heap max heap + /* while( position > 1 && (isMinHeap ? value < heap[position/2] : value > heap[position/2] )){ + heap[position]=heap[position/2]; + position=position/2; + } */ + //variant 2 + + if(isMinHeap){ + while( position > 1 && value < heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value > heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + + heap[position] = value; + } + public int deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + int top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public int peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public int swap(int k){ + int temp = heap[1]; + heap[1]=k; + movingDown(1); + return temp; + } + public void movingDown(int k){ + int temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child] > heap[child+1] ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child] < heap[child+1] ){ // take greater child + child++; + } + } + } + + if( isMinHeap ){ //min heap + if( temp > heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp < heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + } + + k = child; + } + + heap[k]=temp; + } + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k]+" "; + return out; + } + } + // 0 1 2 3 4 5 6 7 + public void go(){ + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + + int n = sc.nextInt(); + // int n = 10; + // int[] array = {5 ,6 ,7 ,4 ,3 ,10 ,20 ,30, 40, 50}; + int index=0; + int num; + Heap left = new Heap(false); // max heap + Heap right = new Heap(true); // min heap + left.insert(Integer.MIN_VALUE); + right.insert(Integer.MAX_VALUE); + int medi; + int temp; + medi=sc.nextInt(); + // medi=array[index]; + // index++; + //StringBuilder sb = new StringBuilder(); + // sb.append(medi+"\n"); + out.println(medi); + for(int i = 1 ; i < n ; i++){ + num=sc.nextInt(); + // num = (int)(Math.random() *1000); + // num=array[index]; + // index++; + + if( left.size == right.size){ + // add to left heap + if ( num <= medi ){ + left.insert(num); + }else{ + left.insert(medi); + medi = num; + if( medi > right.peek() ){ + /* temp = medi; + medi = right.deleteTop(); + right.insert(temp); */ + medi= right.swap(medi); + } + } + + }else{ + // add to right heap + if ( num >= medi ){ + right.insert(num); + }else{ + right.insert(medi); + medi=num; + if( medi < left.peek() ){ + /* temp = medi; + medi=left.deleteTop(); + left.insert(temp);*/ + medi = left.swap(medi); + } + } + + } + + out.println(medi); + } + } + public static void main(String[] args) { - } -} + Week3OnlineMedian ob= new Week3OnlineMedian(); + ob.go(); + } + +} \ No newline at end of file diff --git a/week3/4-Phone-Book-2/PhoneBook.java b/week3/4-Phone-Book-2/PhoneBook.java index 9dade43..40de402 100644 --- a/week3/4-Phone-Book-2/PhoneBook.java +++ b/week3/4-Phone-Book-2/PhoneBook.java @@ -1,28 +1,104 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; + + +/** + * + * @author qvka + */ public class PhoneBook { - public static class Contact { - - public String name; - public int number; - } - - //inserts a new contact - public void insert(Contact contact){ - - } - - //lookup a name and print its phone number - public void lookup(string name){ - - } - - //list all records in an alphabetical order - public void list() { + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args) { + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + MyScanner sc = new MyScanner(); + TreeMap phoneBook = new TreeMap<>(); + int phoneNum; + String name; + String command; + int n = sc.nextInt(); + for(int i = 0 ; i < n ; ++i){ + command = sc.next(); + switch(command){ + case "insert" :{ + phoneNum = sc.nextInt(); + name = sc.next(); + phoneBook.put(name, phoneNum); + }break; + case "lookup" :{ + name = sc.next(); + if(phoneBook.containsKey(name)){ + out.println(phoneBook.get(name)); + }else{ + out.println("NOT FOUND!"); + } + + }break; + case "remove" :{ + name = sc.next(); + phoneBook.remove(name); + }break; + case "list" :{ + StringBuilder sb = new StringBuilder(); + for(Map.Entry entry : phoneBook.entrySet()) { + sb.append(entry.getKey()); + sb.append(" "); + sb.append(entry.getValue()); + sb.append("\n"); + } + int temp = sb.length(); + sb.delete(temp-1, temp); + out.println(sb.toString()); + }break; + } + } + + } - } - - //remove a record for a given name - public void remove(string name) { - - } -} +} \ No newline at end of file diff --git a/week3/5-Bandwidth-Manager/BandwidthManager.java b/week3/5-Bandwidth-Manager/BandwidthManager.java index 1b57b81..f7bc77a 100644 --- a/week3/5-Bandwidth-Manager/BandwidthManager.java +++ b/week3/5-Bandwidth-Manager/BandwidthManager.java @@ -1,12 +1,241 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +/** + * + * @author qvka + */ public class BandwidthManager { + + class Manager{ + private Heap heap; + private Queue[] q; + public Manager(int numOfPriorities){ + heap = new Heap(true); + q = new LinkedList[numOfPriorities]; + for(int i = 0 ; i < numOfPriorities ; i++){ + q[i]=new LinkedList(); + } + } + //receives a packet with specified protocol and payload + public void rcv(String protocol, String payload){ + int priority; + + switch(protocol){ + case "ICMP" : priority = 0; break; + case "UDP" : priority = 1; break; + case "RTM" : priority = 2; break; + case "IGMP" : priority = 3; break; + case "DNS" : priority = 4; break; + case "TCP" : priority = 5; break; + default : throw new RuntimeException("Invalid protocol"); + } + heap.insert(priority); + q[priority].add(payload); + } + + //returns the payload of the packet which should be sent + public String send(){ + + if( heap.size == 0){ + return "Nothing to send!"; + } + int priority = heap.deleteTop(); + return q[priority].poll(); + + } + } + class Heap{ + private int[] heap; // starting from 1 + private static final int CAPACITY = 600000; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new int[CAPACITY]; + } + public Heap(int[] array,boolean isMin){ + this.isMinHeap=isMin; + size= array.length; + heap = new int[size+1]; + System.arraycopy(array, 0, heap, 1, size); + buildHeap(); + } + public int size(){ + return this.size; + } + private void expandHeap(){ + int[] old = heap; + heap = new int[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(int value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value < heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value > heap[position/2] ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + + heap[position] = value; + } + public int deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + int top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public int peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public int swap(int k){ + int temp = heap[1]; + heap[1]=k; + movingDown(1); + return temp; + } + public void movingDown(int k){ + int temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child] > heap[child+1] ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child] < heap[child+1] ){ // take greater child + child++; + } + } + } + + if( isMinHeap ){ //min heap + if( temp > heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp < heap[child] ){ + heap[k] = heap[child]; + }else{ + break; + } + } + + k = child; + } + + heap[k]=temp; + } + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k]+" "; + return out; + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } - //receives a packet with specified protocol and payload - public void rcv(String protocol, String payload){ - - } - - //returns the payload of the packet which should be sent - public String send(){ - - } -} + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public void go(){ + // 0 is the highest priority; + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + Manager m = new Manager(6); + String word,protocol,payload; + int n = sc.nextInt(); + int i=0; + while(i < n){ + word = sc.next(); + switch (word) { + case "rcv": + protocol = sc.next(); + payload = sc.next(); + m.rcv(protocol, payload); + break; + case "send": + out.println( m.send() ); + break; + } + ++i; + } + + } + public static void main(String[] args) { + BandwidthManager bw=new BandwidthManager(); + bw.go(); + } + +} \ No newline at end of file diff --git a/week3/6-Birthday-Ranges-2/BirthdayRanges.java b/week3/6-Birthday-Ranges-2/BirthdayRanges.java index cf95cc7..3d8dd8d 100644 --- a/week3/6-Birthday-Ranges-2/BirthdayRanges.java +++ b/week3/6-Birthday-Ranges-2/BirthdayRanges.java @@ -1,17 +1,223 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; + +/** + * + * @author qvka + */ public class BirthdayRanges { + private class Query{ + private int size; + private int[] tree; + private int realSize; + public Query(int[] sequence){ + // this.arr=new int[sequence.length]; + // System.arraycopy(sequence, 0, arr, 0, sequence.length); + size=sequence.length; + setRealSize(); + this.tree = new int[realSize*2]; + buildTree(sequence); + + } + private void setRealSize(){ + int temp= 1; + while(temp < size){ + temp*=2; + } + this.realSize=temp; + } + private void buildTree(int[] arr){ + //first element of the array is at position realSize + System.arraycopy(arr, 0, tree, realSize, size); + + // starting from the parent of the first element + int nodeIndex=realSize-1; + while(nodeIndex >=1){ + //the number of elements on each depth are equal to the first index + // on that depth + + + tree[nodeIndex]=tree[nodeIndex*2]+tree[nodeIndex*2+1]; + + + nodeIndex--; + } + + } + public void addAtIndex(int index ,int value){ + int position=realSize+index; + int temp = tree[position]; + int difference; + tree[position] += value; + if(tree[position]<0){ + tree[position] = 0; + difference = -temp; + }else{ + difference = value; + } + position/=2; // going up to the parent till root + while(position >= 1 ){ + tree[position] += difference; + position/=2; + } + } + // start inclusive , end exclusive + public int sumAtRange(int start,int end){ + + int totalSum=0; // from 0 to end-1 + int redundancySum=0; //from 0 to begin; + // calculate total sum + totalSum = sumAtRange(end); + redundancySum = sumAtRange(start); + + return totalSum-redundancySum; + } + private int sumAtRange(int end){ + int totalSum=0; + if(end >= size){ + totalSum = tree[1]; // the root + }else{ + + int index = realSize+end; + while(index >= 1 ){ + if(index%2!=0){ // is right child + totalSum += tree[index-1]; // we add left child to the sum + } + index= index/2; // going up + } + } + return totalSum; + } + public void printTree(){ + for(int i = 1 ; i < tree.length ; i++){ + System.out.print(tree[i]+ " "); + } + System.out.println(""); + } + } + private Query qr; + private int[] birthdays; + public BirthdayRanges(int[] a){ + birthdays=new int[366]; + buildArray(a); + qr=new Query(birthdays); + } + private void buildArray(int[] a){ + int day; + for(int i = 0 ; i < a.length ; i++){ + day=a[i]; + birthdays[day]++; + } + + + + + } + // adds people who are born on a specific day + public void add(int day, int numberOfPeople) { + qr.addAtIndex(day,numberOfPeople); + } + + // removes people who are born on a specific day + public void remove(int day, int numberOfPeople) { + // int temp=-1*numberOfPeople; + qr.addAtIndex(day,-numberOfPeople); + // ... + } + + // returns the number of people born in a range + /** + * + * @param startDay inclusive + * @param endDay inclusive + * @return + */ + public int count(int startDay, int endDay) { + return qr.sumAtRange(startDay, endDay+1); + } + public void print(){ + qr.printTree(); + } + + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args){ + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int size; + int commands; + String command; + size = sc.nextInt(); + commands = sc.nextInt(); + int[] arr = new int[size]; + for(int i = 0 ; i < size ; i++){ + arr[i]= sc.nextInt(); + } + BirthdayRanges br= new BirthdayRanges(arr); + + int temp1,temp2; - // adds people who are born on a specific day - public void add(int day, int numberOfPeople) { - // ... - } - - // removes people who are born on a specific day - public void remove(int day, int numberOfPeople) { - // ... - } - - // returns the number of people born in a range - public int count(int startDay, int endDay) { - // ... - } -} + for(int i = 0 ; i < commands; i++){ + command = sc.next(); + temp1 = sc.nextInt(); + temp2 = sc.nextInt(); + switch(command){ + case "count" :{ + out.println(br.count(temp1, temp2)); + }break; + case "add" : { + br.add(temp1, temp2); + }break; + case "remove" : { + br.remove(temp1, temp2); + }break; + } + } + + } + + +} \ No newline at end of file diff --git a/week3/7-Range-Minimum-Query/RMQ.java b/week3/7-Range-Minimum-Query/RMQ.java index 0b676be..0de0fe9 100644 --- a/week3/7-Range-Minimum-Query/RMQ.java +++ b/week3/7-Range-Minimum-Query/RMQ.java @@ -1,12 +1,205 @@ -public class RMQ { +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; + - // sets the value at index +/** + * Range Minimum Query + * @author qvka + */ +public class RMQ { + private Query qr; + + // O (m+ n + log2n) n=size m=realSize + public RMQ(int[] sequence){ + qr=new Query(sequence); + } + /** + * Complexity O(log2 n) + * sets the value at index + * @param index + * @param value + */ public void set(int index, int value) { - // ... + qr.setAtIndex(index, value); } - // returns the minimum value in a range + + /** + * Complexity O(log2 n) + * @param startIndex inclusive + * @param endIndex inclusive + * @return the minimum value in a range + */ public int min(int startIndex, int endIndex) { - // ... + + return qr.minAtRange(startIndex, endIndex); } -} + public void print(){ + qr.printTree(); + } + + private class Query{ + private int size; + private int[] tree; + private int realSize; //closest power of 2 greater or equal to size + // O (m+ n + log2n) n=size m=realSize + public Query(int[] sequence){ + + size=sequence.length; + setRealSize(); + this.tree = new int[realSize*2]; + buildTree(sequence); + + } + /** + * O(log2 n) + */ + private void setRealSize(){ + int temp= 1; + while(temp < size){ + temp*=2; + } + this.realSize=temp; + } + // O(m+n) m=realSize n=size + private void buildTree(int[] arr){ + // complexity of arraycopy is platform dependant but lets assume its O(size) + System.arraycopy(arr, 0, tree, realSize, size); + for(int i = realSize+size; i< tree.length ; i++){ + tree[i]=Integer.MAX_VALUE; + } + // starting from the parent of the first element + int nodeIndex=tree.length/4; + // O (n) n=size + while(nodeIndex >=1){ + //the number of elements on each depth are equal to the first index + // on that depth + int size = nodeIndex; + int temp = nodeIndex; + for(int i = 0 ; i< size ; i++){ + tree[temp]=(tree[temp*2]= 1 ){ + tree[position] = (tree[position*2] < tree[position*2+1])? tree[position*2] : tree[position*2+1]; + position/=2; + } + } + // start inclusive , end exclusive + // O(log2 n) + public int minAtRange(int start,int end){ + + int left=realSize+start; + int right=realSize+end; + if(left==right){ + return tree[left]; + } + int min=tree[left]; + while( left <= right ){ + if(tree[left]< min){ + min=tree[left]; + } + if(tree[right] 0) && (arr[i][index-1] > arr[i][index])){ + temp = arr[i][index-1]; + arr[i][index-1] = arr[i][index]; + arr[i][index] = temp; + counter++; + index--; + } + } + if(maxCounter < counter){ + maxCounter = counter; + maxIndex = i; + } + } + System.out.println(maxIndex+1); + } + +} \ No newline at end of file From 2826cfe7a15b842553fe3759e0922f0e8c5c6cd0 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Thu, 30 Jul 2015 21:00:09 +0300 Subject: [PATCH 03/11] Added solutions --- .../2-Valid-Directories/ValidDirectories.java | 99 +++++- week4/4-Build-Scripts/BuildScripts.java | 124 ++++++++ week4/5-Pouring-Glasses/PouringGlasses.java | 171 +++++++++++ week4/6-Castaway/Castaway.java | 216 +++++++++++++ week5/1-Power-Supply/PowerSupply.java | 222 ++++++++++++++ week5/2-Second-Best-MST/SecondBestMST.java | 288 ++++++++++++++++++ week6/1-Low-Cost-Flights/LowCostFlights.java | 247 +++++++++++++++ week6/2-Navigation/Navigation.java | 270 ++++++++++++++++ week6/5-Rand-Set/RandSet.java | 187 ++++++++++++ week7/1-Word-Dictionary/WordDictionary.java | 115 +++++++ week7/2-Needle-Haystack/NeedleHaystack.java | 111 +++++++ week8/1-Change/Change.java | 71 +++++ .../LongestSubsequence.java | 115 +++++++ 13 files changed, 2232 insertions(+), 4 deletions(-) create mode 100644 week4/4-Build-Scripts/BuildScripts.java create mode 100644 week4/5-Pouring-Glasses/PouringGlasses.java create mode 100644 week4/6-Castaway/Castaway.java create mode 100644 week5/1-Power-Supply/PowerSupply.java create mode 100644 week5/2-Second-Best-MST/SecondBestMST.java create mode 100644 week6/1-Low-Cost-Flights/LowCostFlights.java create mode 100644 week6/2-Navigation/Navigation.java create mode 100644 week6/5-Rand-Set/RandSet.java create mode 100644 week7/1-Word-Dictionary/WordDictionary.java create mode 100644 week7/2-Needle-Haystack/NeedleHaystack.java create mode 100644 week8/1-Change/Change.java create mode 100644 week8/2-Longest-Subsequence/LongestSubsequence.java diff --git a/week4/2-Valid-Directories/ValidDirectories.java b/week4/2-Valid-Directories/ValidDirectories.java index 78537c8..e1b9a0d 100644 --- a/week4/2-Valid-Directories/ValidDirectories.java +++ b/week4/2-Valid-Directories/ValidDirectories.java @@ -1,6 +1,97 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ public class ValidDirectories { + private int visited[]; + private int[][] graph; + private int n; + private boolean isValidDir; + public void go(){ + MyScanner sc = new MyScanner(); + n = sc.nextInt(); + graph = new int[n][n]; + visited = new int[n]; + + for (int i = 0 ; i < n ; ++i){ + for(int y = 0 ; y < n ; ++y){ + graph[i][y] = sc.nextInt(); + } + } + isValidDir = true; + dfs(0); + System.out.println(isValidDir); + } + public void dfs(int v){ + if(!isValidDir){ + return; + } + + int temp; + visited[v] = 1; + for(int i = 0 ; i < n ; ++i){ + temp = graph[v][i]; + if(temp ==1 ){ + if(visited[i] == 0){ + dfs(i); + }else if( visited[i] == 1){ + isValidDir = false; + return; + } + + } + } + visited[v] = 2; + } + public static void main(String[] args) { + ValidDirectories vd = new ValidDirectories(); + vd.go(); + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } - public boolean isValid(int[][] graph) { - // ... - } -} + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file diff --git a/week4/4-Build-Scripts/BuildScripts.java b/week4/4-Build-Scripts/BuildScripts.java new file mode 100644 index 0000000..b2b569a --- /dev/null +++ b/week4/4-Build-Scripts/BuildScripts.java @@ -0,0 +1,124 @@ +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.StringTokenizer; +import java.util.TreeMap; + + +/** + * + * @author qvka + */ +public class BuildScripts { + private boolean hasLoop; + private StringBuilder sb; + ArrayList[] graph; // i-th project - stores which projects it is dependant on + String[] projectNames; // get name by index + int[] visited; + TreeMap map; + public void go(){ + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + sb = new StringBuilder(); + int n = sc.nextInt(); + int temp; + int index; + hasLoop = false; // + int mainProjIndex; + visited = new int[n]; + graph= new ArrayList[n]; // i-th project - stores which projects it is dependant on + projectNames = new String[n]; // get name by index + map = new TreeMap(); // get index by name + for(int i = 0 ; i < n ; ++i){ + projectNames[i] = sc.next(); + map.put(projectNames[i], i); + } + mainProjIndex = map.get(sc.next()); // root + for(int i = 0 ; i < n ; ++i){ + temp = sc.nextInt(); + graph[i] = new ArrayList(); + for(int y = 0 ; y < temp; ++y){ + index = map.get(sc.next()); + graph[i].add(index); + } + } + + visitChildren(mainProjIndex); + if(hasLoop){ + out.println("BUILD ERROR"); + }else{ + sb.delete(sb.length()-1, sb.length()); + out.println(sb.toString()); + } + } + public void visitChildren(int v ){ + if(hasLoop){ + return; + } + int proj; + visited[v] = 1; + for(int i = 0 ; i < graph[v].size(); ++i ){ + proj = graph[v].get(i); + + if(visited[proj] == 0){ // not visited + visitChildren(proj); + } + if(visited[proj] == 1){ + hasLoop = true; + return; + } + // visited[proj] = 0; + } + visited[v]=2; + sb.append(projectNames[v]).append(" "); + } + public static void main(String[] args) { + BuildScripts b = new BuildScripts(); + b.go(); + + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file diff --git a/week4/5-Pouring-Glasses/PouringGlasses.java b/week4/5-Pouring-Glasses/PouringGlasses.java new file mode 100644 index 0000000..e5364b0 --- /dev/null +++ b/week4/5-Pouring-Glasses/PouringGlasses.java @@ -0,0 +1,171 @@ +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author qvka + */ +public class PouringGlasses2 { + private Queue q; + private LinkedList result; + private Tree tree; + private boolean[][] state; + private final int[] c; + private int g,w1,w2,w3; + public PouringGlasses2(int c1, int c2, int c3 , int w1, int w2, int w3, int g){ + tree = new Tree(0,0,w1,w2,w3); + this.c = new int[4]; + this.c[1] = c1; + this.c[2] = c2; + this.c[3] = c3; + this.q = new LinkedList<>(); + this.g = g; + this.w1 = w1; + this.w2 = w2; + this.w3 = w3; + this.state = new boolean[c1+1][c2+1]; + } + public void start(){ + boolean success = false; + int[] w = new int[4]; + int tempFrom,tempTo; + addChildrenToQ(tree.root); + state[tree.root.a][tree.root.b] = true; + Tree.Node node = null; + while(!q.isEmpty()){ + node = q.poll(); + w[1] = node.w1; + w[2] = node.w2; + w[3] = node.w3; + tempTo = w[node.a] + w[node.b]; + if(tempTo > c[node.b]){ + tempTo = c[node.b]; + } + tempFrom = w[node.a] + w[node.b] - c[node.b]; + if(tempFrom < 0){ + tempFrom = 0; + } + w[node.b] = tempTo; + w[node.a] = tempFrom; + node.w1 = w[1]; + node.w2 = w[2]; + node.w3 = w[3]; + if( node.w1 == g || node.w2 == g || node.w3 ==g){ + success = true; + break; + } + if(state[node.w1][node.w2] == false){ + state[node.w1][node.w2] = true; + addChildrenToQ(node); + } + } + if(!success){ + System.out.println("IMPOSSIBLE"); + return; + } + StringBuilder sb = new StringBuilder(); + result = new LinkedList<>(); + while( node != tree.root){ + result.add(node.b); + result.add(node.a); + node = node.parent; + } + System.out.println(result.size()/2); + while(!result.isEmpty()){ + sb.append(result.pollLast()); + sb.append(" "); + sb.append(result.pollLast()); + sb.append("\n"); + } + sb.delete(sb.length()-1, sb.length()); + System.out.println(sb.toString()); + } + public void addChildrenToQ(Tree.Node node){ + int[] w = new int[4]; + w[1] = node.w1; + w[2] = node.w2; + w[3] = node.w3; + if(w[1] != 0 && w[2] != c[2]){ + tree.addChildren(node, 1, 2,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + if(w[1] != 0 && w[3] != c[3]){ + tree.addChildren(node, 1, 3,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + if(w[2] != 0 && w[1] != c[1]){ + tree.addChildren(node, 2, 1,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + if(w[2] != 0 && w[3] != c[3]){ + tree.addChildren(node, 2, 3,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + if(w[3] != 0 && w[1] != c[1]){ + tree.addChildren(node, 3, 1,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + if(w[3] != 0 && w[2] != c[2]){ + tree.addChildren(node, 3, 2,w[1],w[2],w[3]); + q.add(node.children.getLast()); + } + } + + + class Tree{ + public Node root; + public Tree(int a,int b,int w1,int w2,int w3){ + root = new Node(a,b,w1,w2,w3); + root.parent=null; + root.children = new LinkedList<>(); + } + public class Node{ + int a; + int b; + int w1; + int w2; + int w3; + Node parent; + LinkedList children; + public Node(int a,int b,int w1,int w2,int w3){ + this.a = a; + this.b = b; + this.w1 = w1; + this.w2 = w2; + this.w3 = w3; + children = new LinkedList<>(); + } + } + public void addChildren(Node node, int a,int b,int w1,int w2,int w3){ + node.children.add(new Node(a,b,w1,w2,w3)); + node.children.getLast().parent = node; + } + + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int c1,c2,c3,w1,w2,w3,g; + c1 = sc.nextInt(); + c2 = sc.nextInt(); + c3 = sc.nextInt(); + w1 = sc.nextInt(); + w2 = sc.nextInt(); + w3 = sc.nextInt(); + g = sc.nextInt(); + if( w1 == g || w2 == g || w3 == g){ + System.out.println(0); + }else{ + PouringGlasses2 pg = new PouringGlasses2(c1, c2, c3, w1, w2, w3, g); + pg.start(); + } + } + +} \ No newline at end of file diff --git a/week4/6-Castaway/Castaway.java b/week4/6-Castaway/Castaway.java new file mode 100644 index 0000000..e3b402f --- /dev/null +++ b/week4/6-Castaway/Castaway.java @@ -0,0 +1,216 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class Castaway { + private char[][] map; + private ArrayList[] graph; + private Pair[] coordinates; + private boolean[][] visited; + private int[] path; + private int m,n,h; + private Pair start,finish; + private Queue q; + public void go(){ + MyScanner sc = new MyScanner(); + n = sc.nextInt(); + m = sc.nextInt(); + path = new int[28]; // 26 start , 27 finish + Arrays.fill(path, -1); + coordinates = new Pair[28]; + q = new LinkedList(); + start = new Pair(sc.nextInt(),sc.nextInt()); + finish = new Pair(sc.nextInt(),sc.nextInt()); + map = new char[n][]; + String temp; + for(int i = 0; i < n ; ++i){ + temp = sc.nextLine(); + map[i]= temp.toCharArray(); + } + h = sc.nextInt(); + char ch; + for(int i = 0 ; i < n ; ++i){ + for(int y = 0 ; y < m ; ++y){ + ch = map[i][y]; + if( Character.isAlphabetic(ch)){ + coordinates[ (int)ch -97] = new Pair(i,y); + } + } + } + visited = new boolean[n][m]; + coordinates[26] = new Pair(start.a,start.b); + coordinates[27] = new Pair(finish.a,finish.b); + graph = new ArrayList[26]; + for(int i = 0 ; i < 26 ; ++i){ + graph[i] = new ArrayList(); + } + int vert,child; + for(int i = 0 ; i < h ; ++i){ + vert = (int)sc.next().charAt(0) - 97; + child = (int)sc.next().charAt(0) - 97; + graph[vert].add(child); + graph[child].add(vert); + } + + q.add( 26 ); + visited[ start.a][ start.b] = true; + int current; + char symbol; + while(!q.isEmpty() && visited[finish.a][finish.b] == false){ + current = q.poll(); + symbol = map[ coordinates[current].a][ coordinates[current].b]; + if( Character.isAlphabetic(symbol) ){ + addSeaNeighbours(current); + } + addLandNeighbours(current); + + } + if(visited[finish.a][finish.b] == false){ + System.out.println("NNnoooo"); + }else{ + int counter = 0; + int backTrack = 27; + while (backTrack != 26){ + backTrack = path[backTrack]; + counter++; + } + System.out.println(counter); + } + int asd = 213; + } + public void addSeaNeighbours(int p){ + int index = (int)map[coordinates[p].a][coordinates[p].b] - 97; + int child,x,y; + for(int i = 0 ; i < graph[index].size() ; ++i){ + child = graph[index].get(i); + x = coordinates[child].a; + y = coordinates[child].b; + if( visited[x][y] == false){ + visited[x][y] = true; + q.add(child); + path[child] = p; + } + } + } + public void addLandNeighbours(int p){ + int child,x,y; + x = coordinates[p].a; + y = coordinates[p].b; + Queue landQ = new LinkedList(); + Pair temp; + landQ.add(new Pair(x,y)); + char ch; + while(!landQ.isEmpty()){ + temp = landQ.poll(); + ch = map[temp.a][temp.b]; + if ( finish.a == temp.a && finish.b == temp.b){ + visited[temp.a][temp.b] = true; + path[27] = p; + break; + } + if ( Character.isAlphabetic(ch)){ + if(ch != map[x][y]){ + q.add( (int)ch - 97); + path[ (int)ch - 97] = p; + } + } + bfs(temp,landQ); + } + + + } + + + public void bfs(Pair p , Queue que){ + if( p.b > 0 && map[p.a][p.b-1] !='.' ){ //check left + if( visited[p.a][p.b-1] == false){ + visited[p.a][p.b-1] = true; + que.add(new Pair(p.a,p.b-1)); + } + + } + if( p.b < m-1 && map[p.a][p.b+1] !='.'){ // check right + if( visited[p.a][p.b+1] == false){ + visited[p.a][p.b+1] = true; + que.add(new Pair(p.a,p.b+1)); + } + } + if( p.a > 0 && map[p.a-1][p.b] !='.'){ // check right + if( visited[p.a-1][p.b] == false){ + visited[p.a-1][p.b] = true; + que.add(new Pair(p.a-1,p.b)); + } + } + if( p.a < n-1 && map[p.a+1][p.b] !='.'){ // check right + if( visited[p.a+1][p.b] == false){ + visited[p.a+1][p.b] = true; + que.add(new Pair(p.a+1,p.b)); + } + } + } + + public static void main(String[] args) { + Castaway c = new Castaway(); + c.go(); + + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + public class Pair{ + public int a; + public int b; + public Pair(int a ,int b){ + this.a = a; + this.b = b; + } + } +} \ No newline at end of file diff --git a/week5/1-Power-Supply/PowerSupply.java b/week5/1-Power-Supply/PowerSupply.java new file mode 100644 index 0000000..b1e98e4 --- /dev/null +++ b/week5/1-Power-Supply/PowerSupply.java @@ -0,0 +1,222 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class PowerSupply { + private boolean[] visited; + private boolean allVisited; + private Heap heap; + public PowerSupply(int size){ + visited = new boolean[size]; + heap = new Heap(true); // min heap; + } + public void getMinSpan(int[][] graph){ + int sum = 0; + int vertex = 0; + visited[0] = true; + Edge temp; + addChildrenToHeap(vertex,graph); + while(heap.size() > 0){ + temp = heap.deleteTop(); + if( visited[temp.b] == false){ + visited[temp.b] = true; + sum += temp.weigth; + addChildrenToHeap(temp.b, graph); + } + } + + System.out.println(sum); + } + public void addChildrenToHeap(int vertex,int[][] graph){ + for(int i = 0 ; i < graph[vertex].length ; ++i){ + if( visited[i] == false && graph[vertex][i] != 0){ + heap.insert(new Edge(vertex,i, graph[vertex][i])); + // visited[i] = true; + } + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + public class Edge { + public int a; + public int b; + public int weigth; + public Edge(int a , int b ,int weigth){ + this.a = a; + this.b = b; + this.weigth = weigth; + } + } + public class Heap { + private Edge[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[cap]; + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + Edge[] old = heap; + heap = new Edge[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(Edge value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value.weigth < heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value.weigth > heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + heap[position] = value; + } + public Edge deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + Edge top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public Edge peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public void movingDown(int k){ + Edge temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child].weigth > heap[child+1].weigth ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child].weigth < heap[child+1].weigth ){ // take greater child + child++; + } + } + } + if( isMinHeap ){ //min heap + if( temp.weigth > heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp.weigth < heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + } + k = child; + } + heap[k]=temp; + } + + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k].weigth+" "; + return out; + } + + + } + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + int[][] graph = new int[n][n]; + int first , second , length; + for(int i = 0 ; i< n; i++){ + first = sc.nextInt() -1; + second = sc.nextInt() -1; + length = sc.nextInt(); + graph[first][second] = length; + graph[second][first] = length; + } + PowerSupply ps = new PowerSupply(graph.length); + ps.getMinSpan(graph); + + } + +} \ No newline at end of file diff --git a/week5/2-Second-Best-MST/SecondBestMST.java b/week5/2-Second-Best-MST/SecondBestMST.java new file mode 100644 index 0000000..3438c67 --- /dev/null +++ b/week5/2-Second-Best-MST/SecondBestMST.java @@ -0,0 +1,288 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class SecondBestMST { + private boolean[] visited; + private int[][] visitedEdges; + + private LinkedList path; + private Heap heap; + public SecondBestMST(int size){ + visited = new boolean[size]; + heap = new Heap(true); // min heap; + visitedEdges = new int[size][size]; + path = new LinkedList<>(); + } + public void getMinSpan(int[][] graph){ + int sum = 0; + int vertex = 1; + visited[0] = true; + visited[1] = true; + Edge temp; + addEdgesToHeap(vertex,graph); + while(heap.size() > 0){ + temp = heap.deleteTop(); + if( visited[temp.b] == false){ + visited[temp.b] = true; + sum += temp.weigth; + path.add(temp); + visitedEdges[temp.a][temp.b]++; + visitedEdges[temp.b][temp.a]++; + addEdgesToHeap(temp.b, graph); + } + } + heap = new Heap(true); + int secondBest = getSecondBestMST(graph); + + System.out.println(sum + secondBest ); + } + public int countEdges(int[][] graph , int k){ + int counter = 0; + for(int i = 1 ; i < graph[k].length ; ++i){ + if( visitedEdges[k][i] == 1){ + counter++; + } + } + return counter; + } + public int getSecondBestMST(int[][] graph){ + Edge temp; + int a; + int b; + int current; + Edge secondBestEdge; + int currentMin = Integer.MAX_VALUE; + int difference; + int min = Integer.MAX_VALUE; + int aEdges; + int bEdges; + while(!path.isEmpty()){ + temp = path.poll(); + a = temp.a; + b = temp.b; + current = temp.weigth; + + aEdges = countEdges(graph, a); + bEdges = countEdges(graph, b); + if(aEdges > 1){ + addEdgesToHeap2(b, graph); + //a can be disconnected , add edges of b + + } + if(bEdges > 1){ + // b can be disconnected , add edges of a + addEdgesToHeap2(a, graph); + } + if(heap.size > 0){ + secondBestEdge = heap.deleteTop(); + heap = new Heap(true); + currentMin = secondBestEdge.weigth - current; + + if( min > currentMin){ + min = currentMin; + } + } + } + return min; + } + public void addEdgesToHeap2(int vertex,int[][] graph){ + for(int i = 1 ; i < graph[vertex].length ; ++i){ + if( visitedEdges[vertex][i] == 0 && graph[vertex][i] != 0){ + heap.insert(new Edge(vertex,i,graph[vertex][i])); + } + } + } + public void addEdgesToHeap(int vertex,int[][] graph){ + for(int i = 1 ; i < graph[vertex].length ; ++i){ + if( visited[i] == false && graph[vertex][i] != 0){ + heap.insert(new Edge(vertex,i, graph[vertex][i])); + // visited[i] = true; + } + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + public class Edge { + public int a; + public int b; + public int weigth; + public Edge(int a , int b ,int weigth){ + this.a = a; + this.b = b; + this.weigth = weigth; + } + } + public class Heap { + private Edge[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[cap]; + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + Edge[] old = heap; + heap = new Edge[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(Edge value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value.weigth < heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value.weigth > heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + heap[position] = value; + } + public Edge deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + Edge top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public Edge peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public void movingDown(int k){ + Edge temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child].weigth > heap[child+1].weigth ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child].weigth < heap[child+1].weigth ){ // take greater child + child++; + } + } + } + if( isMinHeap ){ //min heap + if( temp.weigth > heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp.weigth < heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + } + k = child; + } + heap[k]=temp; + } + + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k].weigth+" "; + return out; + } + + + } + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + int[][] graph = new int[n][n]; + int first , second , length; + for(int i = 0 ; i< n; i++){ + first = sc.nextInt(); + second = sc.nextInt(); + length = sc.nextInt(); + graph[first][second] = length; + graph[second][first] = length; + } + SecondBestMST ps = new SecondBestMST(graph.length); + ps.getMinSpan(graph); + } + +} \ No newline at end of file diff --git a/week6/1-Low-Cost-Flights/LowCostFlights.java b/week6/1-Low-Cost-Flights/LowCostFlights.java new file mode 100644 index 0000000..8144d1d --- /dev/null +++ b/week6/1-Low-Cost-Flights/LowCostFlights.java @@ -0,0 +1,247 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class LowCostFlights { + private int[] path; + private Heap heap; + private boolean[] visited; + private int minPath; + + public int shortestPath(int from , int to , int[][] graph){ + if( graph[from][to] != 0 ){ + return graph[from][to]; + } + heap = new Heap(true); + path = new int[graph.length]; + visited = new boolean[graph.length]; + minPath = 0; + Edge temp; + visited[from]= true; + Arrays.fill(path, Integer.MAX_VALUE); + path[from] = 0; + addEdgesToHeap(from, graph); + while(heap.size > 0){ + temp = heap.deleteTop(); + + visited[temp.b] = true; + minPath = path[temp.b]; + if(temp.b == to){ + break; + } + addEdgesToHeap(temp.b, graph); + } + return path[to]; + + } + private void addEdgesToHeap(int k , int[][] graph){ + int temp; + for (int i = 0 ; i < graph.length ; ++i){ + if( visited[i] == false && graph[k][i] != 0){ + + heap.insert(new Edge(k,i,graph[k][i])); + temp = minPath + graph[k][i]; + if( temp < path[i]){ + path[i] = temp; + } + + } + } + } + public class Edge { + public int a; + public int b; + public int weigth; + public Edge(int a , int b ,int weigth){ + this.a = a; + this.b = b; + this.weigth = weigth; + } + } + public class Heap { + private Edge[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[cap]; + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + Edge[] old = heap; + heap = new Edge[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(Edge value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value.weigth < heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value.weigth > heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + heap[position] = value; + } + public Edge deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + Edge top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public Edge peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public void movingDown(int k){ + Edge temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child].weigth > heap[child+1].weigth ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child].weigth < heap[child+1].weigth ){ // take greater child + child++; + } + } + } + if( isMinHeap ){ //min heap + if( temp.weigth > heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp.weigth < heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + } + k = child; + } + heap[k]=temp; + } + + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k].weigth+" "; + return out; + } + + + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int n = sc.nextInt(); + int[][] graph = new int[n][n]; + for(int i = 0 ; i < n ; ++i){ + for(int y = 0 ; y < n ; ++y){ + graph[i][y] = sc.nextInt(); + } + } + int m = sc.nextInt(); + int start; + int destination; + LowCostFlights lc = new LowCostFlights(); + for(int i = 0 ; i < m ; ++i){ + start = sc.nextInt(); + destination = sc.nextInt(); + int temp = lc.shortestPath(start, destination, graph); + if( temp == Integer.MAX_VALUE){ + out.println("NO WAY"); + }else{ + out.println(temp); + } + } + } + +} \ No newline at end of file diff --git a/week6/2-Navigation/Navigation.java b/week6/2-Navigation/Navigation.java new file mode 100644 index 0000000..38580a3 --- /dev/null +++ b/week6/2-Navigation/Navigation.java @@ -0,0 +1,270 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.Stack; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class Navigation { + private int[] parents; + private int[] path; + private Heap heap; + private boolean[] visited; + private int minPath; + + public int shortestPath(int from , int to , int[][] graph){ + parents = new int[graph.length]; + heap = new Heap(true); + path = new int[graph.length]; + visited = new boolean[graph.length]; + minPath = 0; + Edge temp; + visited[from]= true; + Arrays.fill(path, Integer.MAX_VALUE); + path[from] = 0; + addEdgesToHeap(from, graph); + while(heap.size > 0){ + temp = heap.deleteTop(); + + visited[temp.b] = true; + minPath = path[temp.b]; + if(temp.b == to){ + break; + } + addEdgesToHeap(temp.b, graph); + } + return path[to]; + + } + public String printPath(int from,int to, int[][] graph){ + Stack stack = new Stack<>(); + int end = to; + while(end != from){ + stack.add(end); + end = parents[end]; + } + stack.add(from); + StringBuilder sb = new StringBuilder(); + while(!stack.isEmpty()){ + sb.append(stack.pop()); + sb.append(" "); + } + int temp = sb.length(); + sb.delete(temp-1, temp); + return sb.toString(); + } + + private void addEdgesToHeap(int k , int[][] graph){ + int temp; + for (int i = 0 ; i < graph.length ; ++i){ + if( visited[i] == false && graph[k][i] != 0){ + + heap.insert(new Edge(k,i,graph[k][i])); + temp = minPath + graph[k][i]; + if( temp < path[i]){ + path[i] = temp; + parents[i]=k; + } + + } + } + } + public class Edge { + public int a; + public int b; + public int weigth; + public Edge(int a , int b ,int weigth){ + this.a = a; + this.b = b; + this.weigth = weigth; + } + } + public class Heap { + private Edge[] heap; // starting from 1 + private static final int CAPACITY = 2; + private int size; + protected boolean isMinHeap; + + public Heap(boolean isMin){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[CAPACITY]; + } + public Heap(boolean isMin,int cap){ //for max heap give argument false + this.isMinHeap = isMin; + size=0; + heap = new Edge[cap]; + } + + public int size(){ + return this.size; + } + private void expandHeap(){ + Edge[] old = heap; + heap = new Edge[heap.length*2]; + System.arraycopy(old, 1, heap, 1, size); + } + public void insert(Edge value){ + if( size == heap.length-1){ + expandHeap(); + } + size++; + int position = size; + if(isMinHeap){ + while( position > 1 && value.weigth < heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + }else{ + while( position > 1 && value.weigth > heap[position/2].weigth ) { + heap[position] = heap[position/2]; + position = position/2; + } + } + heap[position] = value; + } + public Edge deleteTop() throws RuntimeException{ + if(size == 0){ + throw new RuntimeException(); + } + Edge top=heap[1]; + heap[1]=heap[size]; + size--; + movingDown(1); + return top; + } + public Edge peek(){ + if(size == 0){ + throw new RuntimeException(); + } + return heap[1]; + } + private void buildHeap(){ + for(int k = size/2 ; k > 0 ; k--){ + movingDown(k); + } + } + public void movingDown(int k){ + Edge temp = heap[k]; + int child; + while( 2*k <= size ){ + child=2*k; + if( child != size ){ // has sibling ? + if(isMinHeap){ // min heap + if( heap[child].weigth > heap[child+1].weigth ){ // take lesser child + child++; + } + }else{ // max heap + if( heap[child].weigth < heap[child+1].weigth ){ // take greater child + child++; + } + } + } + if( isMinHeap ){ //min heap + if( temp.weigth > heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + }else{ // max heap + if( temp.weigth < heap[child].weigth ){ + heap[k] = heap[child]; + }else{ + break; + } + } + k = child; + } + heap[k]=temp; + } + + @Override + public String toString(){ + String out = ""; + for(int k = 1; k <= size; k++) out += heap[k].weigth+" "; + return out; + } + + + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int n = sc.nextInt(); + int m = sc.nextInt(); + int s = sc.nextInt(); + int c = sc.nextInt(); + int[][] graph = new int[n+1][n+1]; + int row,col; + int weight; + for(int i = 0 ; i < m ; ++i){ + row = sc.nextInt(); + col = sc.nextInt(); + weight = sc.nextInt(); + graph[row][col] = weight; + graph[col][row] = weight; + } + + + Navigation lc = new Navigation(); + + int temp = lc.shortestPath(s, c, graph); + if( temp == Integer.MAX_VALUE){ + out.println("NO WAY"); + }else{ + out.println(temp); + out.println(lc.printPath(s, c, graph)); + } + + } + +} \ No newline at end of file diff --git a/week6/5-Rand-Set/RandSet.java b/week6/5-Rand-Set/RandSet.java new file mode 100644 index 0000000..67a10e2 --- /dev/null +++ b/week6/5-Rand-Set/RandSet.java @@ -0,0 +1,187 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class RandSet { + private ArrayList[] hashTable; + private int mod; + private ArrayList inserted; + public RandSet(){ + this.mod = 1_300_021; + this.inserted = new ArrayList(); + this.hashTable = new ArrayList[mod]; + } + public int hash(int a){ + a = a%mod; + return Math.abs(a); + } + public void insert(int a){ + int hash = hash(a); + if(hashTable[hash] == null){ + hashTable[hash]= new ArrayList(); + }else{ + for(int i = 0 ; i < hashTable[hash].size(); ++i){ + if(hashTable[hash].get(i).number == a){ + // duplicate + return; + } + }// if the cicle above completes it means no duplicate + // we proceed and insert + } + // we add the element with his position to hashTable + // we add element at that position in the inserted vector + hashTable[hash].add(new Pair(a,inserted.size())); + inserted.add(a); + + } + public boolean contains(int a){ + //if inserted is empty its false + if(inserted.isEmpty()){ + return false; + } + int hash = hash(a); + if(hashTable[hash] == null){ + return false; + } + // check all collisions, if we find it return true + for(int i = 0 ; i < hashTable[hash].size() ; ++i){ + if( hashTable[hash].get(i).number == a){ + return true; + } + } + + return false; + } + public void remove(int a){ + if(inserted.isEmpty()){ + return; + } + int hash = hash(a); + int pos = -1; + if( hashTable[hash] == null){ + return; + } + for(int i = 0 ; i < hashTable[hash].size() ; ++i){ + // if we find the element we get its position in the inserted + // and we delete it + if( hashTable[hash].get(i).number == a){ + pos = hashTable[hash].get(i).position; + hashTable[hash].remove(i); + break; + } + } + + // if its the last element , we just delete it + if( pos == inserted.size()-1 ){ + inserted.remove(inserted.size()-1); + }else{ + //else we swap inserted[pos] with inserted[last] + // and update his position in the hash table; + // size--; + inserted.set(pos, inserted.get(inserted.size() -1) ); //set the last element at the deleted position + inserted.remove(inserted.size()-1); + hash = hash( inserted.get(pos)); + changePos(inserted.get(pos),hash,pos); + } + } + public int random(){ + if(inserted.isEmpty()){ + throw new IndexOutOfBoundsException(); + } + int rndm = (int)(Math.random() * inserted.size()); + return inserted.get(rndm); + } + private void changePos(int num, int hash, int pos){ + for(int i = 0 ; i < hashTable[hash].size() ; ++i ){ + if( hashTable[hash].get(i).number == num){ + hashTable[hash].get(i).position = pos; + break; + } + } + } + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + RandSet set = new RandSet(); + int n = sc.nextInt(); + String command; + + for(int i = 0 ; i < n ; ++i){ + command = sc.next(); + + switch(command){ + case "insert" :{ + set.insert(sc.nextInt()); + }break; + case "remove" :{ + set.remove(sc.nextInt()); + }break; + case "contains" :{ + out.println(set.contains(sc.nextInt())); + }break; + case "random" :{ + out.println(set.random()); + }break; + } + } + } + public class Pair{ + public int number; + public int position; + public Pair(int a , int b){ + this.number = a; + this.position = b; + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file diff --git a/week7/1-Word-Dictionary/WordDictionary.java b/week7/1-Word-Dictionary/WordDictionary.java new file mode 100644 index 0000000..70e4964 --- /dev/null +++ b/week7/1-Word-Dictionary/WordDictionary.java @@ -0,0 +1,115 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class WordDictionary { + private PrefixTree trie; + public void go(){ + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + String command; + String word; + trie = new PrefixTree(); + for(int i = 0 ; i < n ; ++i){ + command = sc.next(); + word = sc.next(); + switch(command){ + case "insert" : { + trie.insert(word); + }break; + case "contains" : { + System.out.println(trie.contains(word)); + }break; + } + } + + } + public class PrefixTree{ + private Node root; + public PrefixTree(){ + root = new Node(); + } + public void insert(String a){ + Node current = root; + int temp; + for(int i = 0; i < a.length() ; ++i){ + temp = (int)a.charAt(i) - 97; + if(current.children[temp] == null){ + current.children[temp] = new Node(); + } + current = current.children[temp]; + } + } + public boolean contains(String a){ + Node current = root; + int temp; + for(int i = 0 ; i < a.length() ; ++i){ + temp = (int)a.charAt(i) - 97; + if( current.children[temp] == null){ + return false; + } + current = current.children[temp]; + } + return true; + } + class Node{ + Node[] children; + public Node(){ + children = new Node[26]; + } + } + + } + public static void main(String[] args) { + WordDictionary wd = new WordDictionary(); + wd.go(); + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file diff --git a/week7/2-Needle-Haystack/NeedleHaystack.java b/week7/2-Needle-Haystack/NeedleHaystack.java new file mode 100644 index 0000000..46c424a --- /dev/null +++ b/week7/2-Needle-Haystack/NeedleHaystack.java @@ -0,0 +1,111 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class NeedleHaystack { + public static void countOccuurances(String text,String word){ + + int i = 0; + int size = text.length()-1; + int j = word.length()-1; + int hashWord = hash(word); + int hash = hash(text.substring(i,word.length())); + if(hash == hashWord){ + if( text.substring(i,word.length()).equals(word)){ + System.out.println(i); + } + } + int temp ; + int iVal; + int jVal; + //h(i+1,j+1) = (h(i,j) - value(i)*(BASE^(j-i))) * BASE + value(j+1) + + + while( j < size ){ + iVal = (int)text.charAt(i) - 96; + jVal = (int)text.charAt(j+1) - 96; + hash =(hash - (iVal *(int)Math.pow(200,word.length()-1)))*200 + jVal; + i++; + j++; + if(hash == hashWord){ + + if( text.substring(i,j+1).equals(word)){ + System.out.println(i); + } + } + + } + + } + public static int hash(String a){ + int hash = 0; + int temp; + char ch; + for(int i = 0 ; i < a.length() ; ++i){ + ch = a.charAt(i); + temp = (int) ch -96; + + temp = temp * (int)Math.pow(200, a.length()- 1 -i); + hash += temp; + + } + return hash; + } + public static void main(String[] args) { + + MyScanner sc = new MyScanner(); + String text = sc.nextLine(); + String word = sc.next(); + + NeedleHaystack.countOccuurances(text, word); + + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file diff --git a/week8/1-Change/Change.java b/week8/1-Change/Change.java new file mode 100644 index 0000000..e568b56 --- /dev/null +++ b/week8/1-Change/Change.java @@ -0,0 +1,71 @@ + +import java.util.Scanner; + + +/** + * + * @author qvka + */ +public class ChangeCoins { + private int[][] visited; + private int[] arr = {1,2,5,10,20,50,100}; + private int totalSum; + + public void possiblePermutations(int n){ + totalSum = 0; + Scanner sc = new Scanner(System.in); + visited = new int[n+1][arr.length]; + + int sum = n; //sc.nextInt(); + + sum(sum,6); + System.out.println(totalSum); + } + + public void sum(int sum , int coin){ + if( sum == 0 || coin == 0){ + totalSum++; + return; + } + for(int i = 0 ; i<= coin ; ++i){ + if( sum >= arr[i]){ + sum( sum-arr[i] , i); + } + } + + } + public int sum2(int n){ + visited = new int[n+1][arr.length]; + return sum2(n,6); + } + public int sum2(int sum , int coin){ + if( sum == 0 || coin == 0){ + visited[sum][coin] = 1; + return 1; + } + if(visited[sum][coin] != 0 ){ + return visited[sum][coin]; + }else{ + int total = 0; + for(int i = 0 ; i<= coin ; ++i){ + if( sum >= arr[i]){ + total += sum2( sum-arr[i] , i); + } + } + visited[sum][coin] = total; + return total; + } + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + ChangeCoins cc = new ChangeCoins(); + + int n = sc.nextInt(); + int a = cc.sum2(n); + System.out.println(a); + + } + + +} \ No newline at end of file diff --git a/week8/2-Longest-Subsequence/LongestSubsequence.java b/week8/2-Longest-Subsequence/LongestSubsequence.java new file mode 100644 index 0000000..1ef32b1 --- /dev/null +++ b/week8/2-Longest-Subsequence/LongestSubsequence.java @@ -0,0 +1,115 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class LongestSubsequence { + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + StringBuilder sb = new StringBuilder(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int n = sc.nextInt(); + int arr[] = new int[n]; + for(int i = 0 ; i < n ; ++i){ + arr[i] = sc.nextInt(); + } + + int[] path = new int[n]; + int[] seqSize = new int[n]; + seqSize[0] = 1; + path[0] = -1; + int maxIndex = 1; + int currentMax = -1; + int max = 0; + for(int i = 1 ; i < n ; ++i){ + max = -1; + currentMax = 0; + boolean hasSeq = false; + for(int y = i-1 ; y >= 0 ; y--){ + if( arr[y] < arr[i]){ + + if( seqSize[y] > max){ + currentMax = y; // new current max + max = seqSize[y]; + hasSeq = true; + } + } + } + if( !hasSeq){ + path[i] = -1; + seqSize[i] = 1; + }else{ + path[i] = currentMax; + seqSize[i] = 1 + seqSize[currentMax]; + if( seqSize[i] > seqSize[maxIndex]){ + maxIndex = i; + } + } + } + int size = seqSize[maxIndex]; + int[] result = new int[size]; + System.out.println(size); + for(int i = size-1 ; i >= 0 ; --i){ + result[i] = arr[maxIndex]; + maxIndex = path[maxIndex]; + } + + for(int a : result){ + sb.append(a).append(" "); + } + sb.delete(sb.length()-1, sb.length()); + out.println(sb); + } + + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file From 42a86f7fa40f5e810c7f2ec7a0f1abf64843c89b Mon Sep 17 00:00:00 2001 From: qvkaa Date: Sat, 1 Aug 2015 13:39:41 +0300 Subject: [PATCH 04/11] add solution dna sequence --- week5/3-DNA-Sequence/DnaSequence.java | 211 ++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 week5/3-DNA-Sequence/DnaSequence.java diff --git a/week5/3-DNA-Sequence/DnaSequence.java b/week5/3-DNA-Sequence/DnaSequence.java new file mode 100644 index 0000000..89375ce --- /dev/null +++ b/week5/3-DNA-Sequence/DnaSequence.java @@ -0,0 +1,211 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +/** + * + * @author qvka + */ +public class DnaSequence { + private String[][] graph; + private boolean[][] visitedEdges; + private StringBuilder sb = new StringBuilder(); + private int[] edges; + private HashMap map; + private ArrayList names; + private int n; + public void go(){ + + getData(); + int pos = getStartingPoint(); + int asad=214; + if(pos == -1){ + System.out.println("IMPOSSIBLE"); + return; + } + findEulerPath(pos); + } + private void findEulerPath(int start){ + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int current = start; + sb.append( names.get(start)); + int next; + int counter = 0; + do{ + next = findLegitPath(current); + if( next != -1){ + sb.append( graph[current][next]).append( names.get(next)); + counter++; + current = next; + } + }while( next != -1); + if( counter == n){ + out.println(sb.toString()); + }else{ + out.println("IMPOSSIBLE"); + } + } + private int findLegitPath(int vertex){ + boolean isBridge = true; + for(int i = 0 ; i < graph[vertex].length ; ++i){ + if( graph[vertex][i] != null && visitedEdges[vertex][i] == false){ + if( edges[vertex] == 1){ // if the current vertex has only one path we take it + isBridge = false; + }else if( edges[i] == 1){ // if the current vertex has more paths we dont take the dead end + isBridge = true; + }else{ + isBridge = isBridge(vertex,i); // we check to see if this edge is a bridge + } + } + if( !isBridge){ + visitedEdges[vertex][i] = true; + visitedEdges[i][vertex] = true; + edges[vertex]--; + edges[i]--; + return i; // we return the index of the vertex if its not a bridge + } + } + return -1; // return -1 if its a bridge + } + private boolean isBridge(int first, int second){ + int size = visitedEdges.length; + boolean[][] visited = new boolean[size][size]; + for(int i = 0 ; i < size ; ++i){ + System.arraycopy(visitedEdges[i], 0, visited[i] , 0, size); + } + visited[first][second] = true; + visited[second][first] = true; + int edge; + Queue q = new LinkedList(); + q.add(first); + while(!q.isEmpty()){ // if we can reach second by other path its not a bridge + edge = q.poll(); + if( edge == second ){ + return false; + } + bfs(edge,q,visited); + } + return true; + } + private void bfs(int vertex, Queue q , boolean[][] visited){ + int edge; + for(int i = 0 ; i < graph[vertex].length ; ++i){ + if( graph[vertex][i] != null && visited[vertex][i] == false){ + q.add(i); + visited[vertex][i] = true; + visited[i][vertex] = true; + } + } + } + private int getStartingPoint(){ + int count = 0 ; + int pos = 0 ; + for(int i = 0 ; i < edges.length ; ++i){ + if( edges[i] % 2 == 1){ + pos = i; + count++; + } + } + if( count == 2 || count ==0){ + return pos; + }else{ + return -1; + } + } + private void getData(){ + MyScanner sc = new MyScanner(); + n = sc.nextInt(); + names = new ArrayList(); + map = new HashMap(); + sb = new StringBuilder(); + String[] dnaSamples = new String[n]; + int index = 0; + int firstIndex; + int secondIndex; + String dna,first,mid,second; + for(int i = 0 ; i < n ; ++i){ + dna = sc.next(); + dnaSamples[i] = dna; + first = dna.substring(0,3); + second = dna.substring( dna.length()-3); + if(!map.containsKey(first)){ + map.put(first, index); + names.add(first); + index++; + } + if(!map.containsKey(second)){ + map.put(second,index); + names.add(second); + index++; + } + } + graph = new String[index][index]; + visitedEdges = new boolean[index][index]; + edges = new int[index]; + for(int i = 0 ; i < n ; ++i){ + dna = dnaSamples[i]; + first = dna.substring(0,3); + mid = dna.substring(3, dna.length()-3); + second = dna.substring( dna.length()-3); + firstIndex = map.get(first); + secondIndex = map.get(second); + graph[firstIndex][secondIndex] = mid; + graph[secondIndex][firstIndex] = mid; + edges[firstIndex]++; + edges[secondIndex]++; + } + } + public static void main(String[] args) { + DnaSequence dna = new DnaSequence(); + dna.go(); + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file From 945dda79f83445c78165f67ed40487030ddfe419 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Mon, 3 Aug 2015 18:18:35 +0300 Subject: [PATCH 05/11] Add bank robbery solution --- week9/1-Bank-Robbery/BankRobbery.java | 118 ++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 week9/1-Bank-Robbery/BankRobbery.java diff --git a/week9/1-Bank-Robbery/BankRobbery.java b/week9/1-Bank-Robbery/BankRobbery.java new file mode 100644 index 0000000..b62b50f --- /dev/null +++ b/week9/1-Bank-Robbery/BankRobbery.java @@ -0,0 +1,118 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class BankRobbery { + private boolean[][] graph; + private int[] robberVisited; + private int[] policeVisited; + private int[] path; + private int bank; + private int police; + private int helicopter; + public void go(){ + getData(); + int robberPath = getShortestPath(bank, helicopter, robberVisited) ; + int policePath = getShortestPath(police, helicopter, policeVisited); + System.out.println(policePath - robberPath - 1); + } + private void getData(){ + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + int m = sc.nextInt(); + n++; // not zero based + graph = new boolean[n][n]; + robberVisited = new int[n]; + Arrays.fill(robberVisited, -1); + policeVisited = new int[n]; + Arrays.fill(policeVisited, -1); + path = new int[n]; + int v1,v2; + for(int i = 0 ; i < m ; ++i){ + v1 = sc.nextInt(); + v2 = sc.nextInt(); + graph[v1][v2] = true; + graph[v2][v1] = true; + } + bank = sc.nextInt(); + police = sc.nextInt(); + helicopter = sc.nextInt(); + } + private int getShortestPath(int start,int end, int[] visited){ + Queue q = new LinkedList(); + q.add(start); + int current; + visited[start] = 0; + while( !q.isEmpty()){ + current = q.poll(); + if(end == current){ + break; + } + addNeighboursToQ(q,current,visited); + } + return visited[end]; + } + private void addNeighboursToQ(Queue q, int vertex , int[] visited){ + for(int i = 0 ; i < graph[vertex].length ; ++i){ + if( graph[vertex][i] == true && visited[i] == -1){ + visited[i] = visited[vertex]+1; + q.add(i); + } + } + } + public static void main(String[] args) { + BankRobbery br = new BankRobbery(); + br.go(); + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file From dfcdaa5a16174b1b94d22bc9da4b0971b6a399d0 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Mon, 3 Aug 2015 20:49:07 +0300 Subject: [PATCH 06/11] added solution for light switches --- week9/2-Light-Switches/LightBulbs.java | 116 +++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 week9/2-Light-Switches/LightBulbs.java diff --git a/week9/2-Light-Switches/LightBulbs.java b/week9/2-Light-Switches/LightBulbs.java new file mode 100644 index 0000000..b224c5c --- /dev/null +++ b/week9/2-Light-Switches/LightBulbs.java @@ -0,0 +1,116 @@ + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + + + +/** + * + * @author qvka + */ +public class LightBulbs { + public void go(){ + Scanner sc = new Scanner(System.in); + int state = 0; + String temp; + int[] switches = new int[17]; + int bit; + for(int i = 15 ; i >= 0 ; --i){ + temp = sc.next(); + if( temp.equals("on") ){ + state = state | ( 1 << i); + } + } + int tempState; + int num; + for(int y = 1 ; y < 17 ; ++y){ + tempState = 0; + for(int i = 15 ; i >= 0 ; --i){ + num = sc.nextInt(); + if( num == 1){ + switches[ y ] = switches[y] | ( num << i); + } + } + } + + bfs(state , switches); + + int a = 1; + } + private void bfs(int state, int[] switches){ + boolean[] visited = new boolean[ (int)Math.pow(2, 16)]; + Tree tree = new Tree(state); + Tree.Node current = null; + Queue q = new LinkedList(); + q.add(tree.root); + boolean isPossible = false; + while( !q.isEmpty()){ + current = q.poll(); + if(current.state == 0){ + isPossible = true; + break; + } + if( visited[current.state] == false){ + visited [current.state] = true; + for(int i = 1 ; i < 17 ; ++i){ + tree.addChild(current, i , switches); + q.add(current.children.getLast()); + visited[current.state] = true; + } + } + } + if(!isPossible){ + System.out.println("Can't be done"); + }else{ + LinkedList result = new LinkedList(); + while( current.parent != null){ + result.add(current.switchIndex); + current = current.parent; + } + StringBuilder sb = new StringBuilder(); + while(!result.isEmpty()){ + sb.append(result.pollLast()).append(" "); + } + sb.delete(sb.length()-1, sb.length()); + System.out.println(sb.toString()); + } + + } + private int getState(int state , int index , int[] switches){ + // y = x ^ (1< children; + public Node(int state){ + this.state = state; + this.switchIndex = -1; + this.children = new LinkedList(); + } + public Node(int state , int switchIndex , int[] switches){ + this.switchIndex = switchIndex; + this.state = getState ( state , switchIndex , switches); + this.children = new LinkedList(); + } + } + public void addChild(Node current , int index , int[] switches){ + current.children.add( new Node( current.state , index , switches)); + current.children.getLast().parent = current; + } + } + +} \ No newline at end of file From c8790ec9acf71207091b0b23dcbb3f4ccd0f96ea Mon Sep 17 00:00:00 2001 From: qvkaa Date: Tue, 4 Aug 2015 22:08:10 +0300 Subject: [PATCH 07/11] Added solution for vitosha run --- week6/3-Vitosha-Run/VitoshaRun.java | 145 ++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 week6/3-Vitosha-Run/VitoshaRun.java diff --git a/week6/3-Vitosha-Run/VitoshaRun.java b/week6/3-Vitosha-Run/VitoshaRun.java new file mode 100644 index 0000000..cffaa97 --- /dev/null +++ b/week6/3-Vitosha-Run/VitoshaRun.java @@ -0,0 +1,145 @@ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + + + +/** + * + * @author qvka + */ +public class VitoshaRun { + + public int findShorthestPath(int startA, int startB , int finishA , int finishB , int[][] matrix){ + int n = matrix.length; + + boolean[][] visited = new boolean[n][n]; + int[][] currentDistance = new int[n][n]; + for(int i = 0 ; i < n ; ++i){ + Arrays.fill(currentDistance[i], Integer.MAX_VALUE); + } + Vertex current; + PriorityQueue heap = new PriorityQueue(); + heap.offer( new Vertex(startA, startB, 0)); + while(!heap.isEmpty()){ + current = heap.poll(); + if( visited[ current.a][current.b] == false){ + visited[current.a][current.b] = true; + if( visited[finishA][finishB] == true){ + break; + } + addNeighbours(heap,current,matrix,visited,currentDistance); + } + } + if(visited[finishA][finishB] == true){ + return currentDistance[finishA][finishB]; + }else{ + return -1; + } + } + private void addNeighbours(PriorityQueue heap,Vertex current, int[][] matrix,boolean[][] visited , int[][] currentDistance ){ + int row,col; + row = current.a-1; + int weigth; + for(int i = 0 ; i < 3 ; ++i){ + col = current.b-1; + for(int y = 0 ; y < 3 ; ++y){ + if( (row > -1) && (row < matrix.length) && (col > -1) && (col < matrix.length)){ + if(visited[row][col] == false){ + weigth = Math.abs ( matrix[current.a][current.b] - matrix[row][col]) +1; + weigth += current.weigth; + if( weigth < currentDistance[row][col]){ + currentDistance[row][col] = weigth; + heap.offer(new Vertex(row,col,weigth)); + } + } + } + col++; + } + row++; + } + } + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + int n = sc.nextInt(); + int startRow = sc.nextInt(); + int startCol = sc.nextInt(); + int finishRow = sc.nextInt(); + int finishCol = sc.nextInt(); + int[][] matrix = new int[n][n]; + for(int i = 0 ; i < n ; ++i){ + for (int y = 0 ; y < n ; ++y){ + matrix[i][y] = sc.nextInt(); + } + } + VitoshaRun vr = new VitoshaRun(); + int minutes = vr.findShorthestPath(startCol, startCol, finishCol, finishCol, matrix); + System.out.println(minutes); + } + public class Vertex implements Comparable{ + public int a; + public int b; + public int weigth; + public Vertex( int a , int b, int weigth){ + this.a = a; + this.b = b; + this.weigth = weigth; + } + + @Override + public int compareTo(Vertex o) { + if( this.weigth > o.weigth){ + return 1; + }else if( this.weigth < o.weigth){ + return -1; + }else{ + return 0; + } + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file From a7abae5d6a3ef05e60e429d2e8866202f8fcd937 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Wed, 5 Aug 2015 01:33:10 +0300 Subject: [PATCH 08/11] Added solution for k intersect --- week6/6-K-Intersect/KIntersect.java | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 week6/6-K-Intersect/KIntersect.java diff --git a/week6/6-K-Intersect/KIntersect.java b/week6/6-K-Intersect/KIntersect.java new file mode 100644 index 0000000..6f3f410 --- /dev/null +++ b/week6/6-K-Intersect/KIntersect.java @@ -0,0 +1,93 @@ + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; + + +/** + * + * @author qvka + */ +public class KIntersecti { + + + public static void main(String[] args) { + MyScanner sc = new MyScanner(); + PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out),true); + int n = sc.nextInt(); + int value,key; + String line; + HashMap map = new HashMap(); + Set s = new HashSet(); + StringTokenizer tokenizer; + for(int i = 0 ; i < n ; ++i){ + tokenizer = new StringTokenizer(sc.nextLine()," "); + s.clear(); + while(tokenizer.hasMoreTokens()){ + s.add( Integer.parseInt(tokenizer.nextToken())); + } + for(int setEntry : s){ + if(!map.containsKey(setEntry)){ + map.put(setEntry, 1); + }else{ + map.put(setEntry, map.get(setEntry)+1); + } + } + } + for(Map.Entry entry : map.entrySet()){ + key = entry.getKey(); + value = entry.getValue(); + if(value == n){ + out.println(key); + } + } + } + public static class MyScanner { + BufferedReader br; + StringTokenizer st; + + public MyScanner() { + br = new BufferedReader(new InputStreamReader(System.in)); + } + + String next() { + while (st == null || !st.hasMoreElements()) { + try { + st = new StringTokenizer(br.readLine()); + } catch (IOException e) { + e.printStackTrace(); + } + } + return st.nextToken(); + } + + int nextInt() { + return Integer.parseInt(next()); + } + + long nextLong() { + return Long.parseLong(next()); + } + double nextDouble() { + return Double.parseDouble(next()); + } + + String nextLine(){ + String str = ""; + try { + str = br.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return str; + } + } + +} \ No newline at end of file From 85d61558babbe6cd7baa2da13bedaaf2634b9998 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Thu, 10 Sep 2015 22:46:53 +0300 Subject: [PATCH 09/11] Update Vector.java --- week1/1-Vector/Vector.java | 143 +++++++++++++++++++++++++++---------- 1 file changed, 107 insertions(+), 36 deletions(-) diff --git a/week1/1-Vector/Vector.java b/week1/1-Vector/Vector.java index b39337b..ae04569 100644 --- a/week1/1-Vector/Vector.java +++ b/week1/1-Vector/Vector.java @@ -1,44 +1,115 @@ -public class Vector { - // Adds value at a specific index in the Vector. - // Complexity: O(n) - public void insert(int index, T value) { - // ... - } +/** + * + * @author qvka + */ +public class Vector { + private T[] array; + private int size; + public Vector(){ + this.size = 0; + this.array = (T[]) new Object[8]; + } + public Vector(int capacity){ + this.size = 0; + this.array = (T[]) new Object[capacity]; + } + // Adds value at a specific index in the Vector. + // Complexity: O(n) + public void insert(int index, T value) { + if(index > size || index < 0){ + throw new IndexOutOfBoundsException(); + } + if(size == array.length){ + expand(); + } + int i = size; + + while( i > index ){ + array[i] = array[i-1]; + i--; + } + array[index] = value; + size++; + } - // Adds value to the end of the Vector. - // Complexity: O(1) - public void add(T value) { - // ... - } + // Adds value to the end of the Vector. + // Complexity: O(1) + public void add(T value) { + if(size == array.length){ + expand(); + } + array[size] = value; + size++; + } + private void expand(){ + T[] temp = (T[]) new Object[array.length*2]; + System.arraycopy(array, 0, temp, 0, size); + array = temp; + } + // Returns value at a specific index in the Vector + // Complexity: O(1) + public T get(int index) { + if( index >= size || index < 0){ + throw new IndexOutOfBoundsException(); + } + return (T)array[index]; + } - // Returns value at a specific index in the Vector - // Complexity: O(1) - public T get(int index) { - // ... - } + // Removes element at the specific index + // Complexity: O(n) + public void remove(int index) { + if(size == 0){ + return; + } + if( index < 0 || index >= size){ + throw new IndexOutOfBoundsException(); + } + int i = index+1; + while( i < size){ + array[i-1] = array[i]; + i++; + } + size--; + } - // Removes element at the specific index - // Complexity: O(n) - public void remove(int index) { - // ... - } + // Removes element at the last index + // Complexity: O(1) + public T pop() { + if(size == 0){ + return null; + } + size--; + return (T)array[size+1]; + } - // Removes element at the last index - // Complexity: O(1) - public T pop() { - // ... - } + // Returns the number of elements in the Vector. + // Complexity: O(1) + public int size() { + return size; + } - // Returns the number of elements in the Vector. - // Complexity: O(1) - public int size() { - // ... - } + // Returns the total capacity of the Vector. + // Complexity: O(1) + public int capacity() { + return array.length; + } - // Returns the total capacity of the Vector. - // Complexity: O(1) - public int capacity() { - // ... - } + public static void main(String[] args) { + Vector a = new Vector(5); + System.out.println(a.capacity() + " " +a.size()); + a.add(2); + System.out.println(a.get(0)); + a.insert(0, 1); + System.out.println(a.get(0)); + a.remove(0); + a.add(6); + a.add(6); + a.add(6); + a.add(6); + a.add(6); + a.add(6); + System.out.println(a.capacity()); + + } } From 0fb8c9de36d1df31247641caa913cbf6099c3692 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Sat, 12 Sep 2015 12:24:29 +0300 Subject: [PATCH 10/11] Update Queue.java --- week1/2-Queue/Queue.java | 57 +++++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/week1/2-Queue/Queue.java b/week1/2-Queue/Queue.java index 1570d9c..335cd15 100644 --- a/week1/2-Queue/Queue.java +++ b/week1/2-Queue/Queue.java @@ -1,26 +1,41 @@ -class Queue { - // Adds value to the end of the Queue. - // Complexity: O(1) - public void push(T value) { - // ... - } +import java.util.LinkedList; + + +class Queue { + private LinkedList q; + public Queue(){ + q = new LinkedList(); + } + // Adds value to the end of the Queue. + // Complexity: O(1) + public void push(T value) { + q.add(value); + } - // Returns value from the front of the Queue and removes it. - // Complexity: O(1) - public T pop() { - // ... - } + // Returns value from the front of the Queue and removes it. + // Complexity: O(1) + public T pop() { + if(q.size() < 1){ + return null; + } + T temp = q.getFirst(); + q.removeFirst(); + return temp; + } - // Returns value from the front of the Queue without removing it. - // Complexity: O(1) - public T peek() { - // ... - } + // Returns value from the front of the Queue without removing it. + // Complexity: O(1) + public T peek() { + if(q.size() < 1){ + return null; + } + return q.getFirst(); + } - // Returns the number of elements in the Queue. - // Complexity: O(1) - public int size() { - // ... - } + // Returns the number of elements in the Queue. + // Complexity: O(1) + public int size() { + return q.size(); + } } From cb0f5767e0c09b40d9022b79a0e41e459ae6d115 Mon Sep 17 00:00:00 2001 From: qvkaa Date: Sat, 12 Sep 2015 19:58:22 +0300 Subject: [PATCH 11/11] Update README.md --- week1/4-Complexities/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/week1/4-Complexities/README.md b/week1/4-Complexities/README.md index f3a8043..59aed3e 100644 --- a/week1/4-Complexities/README.md +++ b/week1/4-Complexities/README.md @@ -15,7 +15,7 @@ is_prime(number) { } ``` -Complexity: ... +Complexity: O(n) ## Checking if a string is palindrome @@ -37,7 +37,7 @@ is_palindrome(string) { } ``` -Complexity: ... +Complexity: O(n) ## Summing elements of a matrix @@ -49,7 +49,7 @@ for (i = 0; i < n; i++) { } ``` -Complexity: ... +Complexity: O(n*m) ## Counting 1 @@ -61,7 +61,7 @@ for (i = 0; i < n; i++) { } ``` -Complexity: ... +Complexity: O(n^2) ## Counting 2 @@ -73,4 +73,4 @@ for (i = 0; i < n; i++) { } ``` -Complexity: ... +Complexity: O(n logn)