Sunday, 30 October 2016

Priority_Queue in STL


Hello guys , This time I am gonna tell you about priority_queue.

Priortiy_queue is a container adaptor,meaning that it is implemented on top of some underlying container type. By default that container
is Vector but a different type can be used too.

Before moving on i would like you to tell what is a Max_Heap:
please go to this link if you know nothing like JOHN SNOW about HEAP

priority_queue is just like a normal  queue except the element removed from the queue is always the greatest among the all the elements of the queue , thus this
container is usually used to replicate Max Heap in C++ .  Elements in Priority_queue can be inserted or removed in a time complexity of O(log(n)).

functions used :
 1. empty()
 2. size()
 3. top()
 4.push_back()
 5. pop_back()
 6. make_heap()
 7. push_heap()
 8. pop_heap()
 9. reverse()
 10.swap(x,y) -> exchanges the content of X and Y . X and Y are the priority_queue containers of the same type. Their size may be different
 11.compare -> used to determine whether one element is greater than the other element or not.
 if Compare(x,y) is true , then x is smaller than y

We can use any kind of container to store a priority_queue like , map , queue , dequeue etc
We can reverse the priorities also

example :

Here we are making a Heap without using a priority_queue
//make_heap,push_heap,pop_heap,reverse: -> all are included from #include<algorithm> */


#include<iostream>
#include<algorithm>
#include<queue>
#include <vector>
using namespace std;
int main()
{
    int myints[] ={10,20,30,5,15};
    vector<int>v(myints,myints+5);
    make_heap(v.begin(),v.end());
    cout<<"initial  max heap: "<<v.front()<<endl;
    pop_heap(v.begin(),v.end());
    v.pop_back(); // pops the last elemnt from the vector
    v.push_back(99);
    push_heap(v.begin(),v.end());
    cout<<"max heap after push: "<<v.front();
    sort_heap(v.begin(),v.end()); // sorts th element of the heap
    cout<<"final sorted range: ";
    for(int i =0;i<v.size();i++)
    {
        cout<<v[i]<<endl;
    }
    reverse(v.begin(),v.end()); // now the vector is reversed

    for(int i =0;i<v.size();i++)
    {
        cout<<v[i]<<endl;
    }
}}

/*The most important property of priority_queue is that it  does not allow iterations through its elements */
#include<iostream>
#include<queue>
 using namespace std;
 int main()
 {
    priority_queue<int>pq;
    priority_queue<int>zz;
    pq.push(10);
     pq.push(30);
    pq.push(40);
    pq.push(90);
    pq.push(100);
    pq.push(60);
    pq.push(10);
     zz.push(200);
     zz.push(530);
    zz.push(420);
    zz.push(910);
    zz.push(105);
    zz.push(160);
    zz.push(80);
    cout<<pq.size()<<endl;
    cout<<pq.top()<<endl;
    pq.pop();
    cout<<pq.top()<<endl;
    pq.pop();
    cout<<pq.top()<<endl;
    pq.pop();
    cout<<pq.top()<<endl;
    pq.pop();
    cout<<pq.top()<<endl;
    pq.pop();

 }

    /* Use of Swap() in priority_queue: */
#include<iostream>
#include<queue>
 using namespace std;
 int main()
 {
    priority_queue<int>pq;
    priority_queue<int>zz;
    pq.push(10);
     pq.push(30);
    pq.push(40);
    pq.push(90);
    pq.push(100);
    pq.push(60);
    pq.push(10);
     zz.push(200);
     zz.push(530);
    zz.push(420);
    zz.push(910);
    zz.push(105);
 
    swap(pq,zz);
    cout<<"size of pq: "<<pq.size()<<" size of zz: "<<zz.size()<<endl;
}
/*  if we can create heap using make_heap , push_heap and pop_heap  then why do we use priority_queue ??
    it  is because of the restriction of iteration of element in priority_queue
 **** Have you ever wondered why pop() returns void instead of  value_type ??
     

*/
/* A priority_queue for user defined objects :->
  *** priority_queue  can be used in many real life situations also
    for example :
*/

#include<iostream>
#include<queue>
#include<vector>
    class Toast
{
    public :
        int bread;
        int butter;
        Toast(int bread ,int butter)
            :bread(bread),butter(butter)
            {
            }
 };

// how  will you sort a toast given that toast has a value based upon the amount of butter and bread.
//This is done by creating a structure implementing an operator() and efficiently doing less than comparision

struct ToastCompare
{
    bool operator()(const Toast &t1 ,const Toast &t2)const
    {
        int t1value = t1.bread*1000 + t1.butter;
        int t2value = t2.bread*1000 + t2.butter;
        return t1value<t2value;
    }
};


using namespace std;
int main()
{
    Toast toast1(2,200);
    Toast toast2(1,300);
    Toast toast3(1,10);
    Toast toast4(3,1);
   
    priority_queue<Toast,vector<Toast>,ToastCompare>q;
    q.push(toast1);
    q.push(toast2);
    q.push(toast3);
    q.push(toast4);
    while(!q.empty())
    {
        Toast t = q.top();
        cout<<"bread: "<<t.bread<<"  butter: "<<t.butter<<endl;
        q.pop();
    }

}
















Monday, 24 October 2016

c++ stl map

Hello everyone!

This time I am going to tell you about  MAP -> a very very important stuff that saves lot of your time during a coding contest .
Just like stack , queue ,      map is also a container class of STL .

A map contains two values , one of them is the key and other is the value stored at that key . A particular value can be accessed or modified by using its key . A key of a value is unique i.e map has unique keys which can not be modified .
following example will clarify everything :

#include<iostream>
#include<string.h>
#include<string>
#include<map>

using namespace std;

int main()
{
     map<string,int>employees;   // here the first one(string) is the key and int is the value stored at
                                                   //at that key
     employees.insert(pair<string,int>("vikram",1932)) ; //inserting values into map
      employees.insert(pair<string,int>("Rahul" ,1231)) ;
     employees.insert(pair<string,int>("arjun" ,1012)) ;
 
     cout<<"map size : "<<employees.size()<<endl; // to get  the size of map
     // iterating thorugh a map
    // In STL iterators provide a means for accessing data stored in container classes such a vector
   //  list , map etc .
    // declaring an iterator ->  class_name<template_parameters>::iterator name
   map<string,int>::iterator it = employees.begin(); // referencing iterator to the beginning of map
   for(it; it!= employees.end() ; it++ )
   {
         cout<< it->first<<"  "<<it->second<<endl;  // first gives  you the key ,, second gives you value
   }cout<<endl;
    //iterating the map in reverse manner
 
    map<string,int>::reverse_iterator  bt =  employees.rbegin();
   for(bt ;  bt!= employees.rend(); bt++)
   {
         cout<< bt->first<<"  "<<bt->second<<endl;
   }



   /*  to check whether a key is present in the map */
   // suppose we want to check  if  a key named "arjun" is present in the map or not
   // for this we use map.count(key_name) ;  it returns value >0 if that key is already in map else 0

   if( employees.count("arjun")>0){cout<<"this key is present "<<endl; }
 
      /*  accessing/modifying  value stored at a particular key*/
      // accessing :
      cout<<"value stored at arjun : "<<employees.at("arjun")<<endl;
     //modifying :
      employees.at("arjun") = 500;
    // inserting new key using [ ] :
     employees ["tata"] = 123;
      cout<<"value stored at tata : "<<employees.at("tata")<<endl;
 
 }

output is :
map size : 3
Rahul  1231
arjun  1012
vikram  1932

vikram  1932
arjun  1012
Rahul  1231
this key is present
this key is present
value stored at arjun : 1012
value stored at tata : 123
  
you can see that value stored in a map is already sorted . Time complexity of std:: map is of log(n)

I will be writing about tie complexity in another post .

If regarding map you have any doubt , visit this page this one

Here are some questions which can be solved using map . Please go through this link  if you hate Ramsay Bolton and enjoyed the Battle of Bastards :) 


c++ stl map

Hello everyone!

This time I am going to tell you about  MAP -> a very very important stuff that saves lot of your time during a coding contest .
Just like stack , queue ,      map is also a container class of STL .

A map contains two values , one of them is the key and other is the value stored at that key . A particular value can be accessed or modified by using its key . A key of a value is unique i.e map has unique keys which can not be modified .
following example will clarify everything :

#include<iostream>
#include<string.h>
#include<string>
#include<map>

using namespace std;

int main()
{
     map<string,int>employees;   // here the first one(string) is the key and int is the value stored at
                                                   //at that key
     employees.insert(pair<string,int>("vikram",1932)) ; //inserting values into map
      employees.insert(pair<string,int>("Rahul" ,1231)) ;
     employees.insert(pair<string,int>("arjun" ,1012)) ;
 
     cout<<"map size : "<<employees.size()<<endl; // to get  the size of map
     // iterating thorugh a map
    // In STL iterators provide a means for accessing data stored in container classes such a vector
   //  list , map etc .
    // declaring an iterator ->  class_name<template_parameters>::iterator name
   map<string,int>::iterator it = employees.begin(); // referencing iterator to the beginning of map
   for(it; it!= employees.end() ; it++ )
   {
         cout<< it->first<<"  "<<it->second<<endl;  // first gives  you the key ,, second gives you value
   }cout<<endl;
    //iterating the map in reverse manner
 
    map<string,int>::reverse_iterator  bt =  employees.rbegin();
   for(bt ;  bt!= employees.rend(); bt++)
   {
         cout<< bt->first<<"  "<<bt->second<<endl;
   }



   /*  to check whether a key is present in the map */
   // suppose we want to check  if  a key named "arjun" is present in the map or not
   // for this we use map.count(key_name) ;  it returns value >0 if that key is already in map else 0

   if( employees.count("arjun")>0){cout<<"this key is present "<<endl; }
 
      /*  accessing/modifying  value stored at a particular key*/
      // accessing :
      cout<<"value stored at arjun : "<<employees.at("arjun")<<endl;
     //modifying :
      employees.at("arjun") = 500;
    // inserting new key using [ ] :
     employees ["tata"] = 123;
      cout<<"value stored at tata : "<<employees.at("tata")<<endl;
 
 }

output is :
map size : 3
Rahul  1231
arjun  1012
vikram  1932

vikram  1932
arjun  1012
Rahul  1231
this key is present
this key is present
value stored at arjun : 1012
value stored at tata : 123
  
you can see that value stored in a map is already sorted . Time complexity of std:: map is of log(n)

I will be writing about tie complexity in another post .

If regarding map you have any doubt , visit this page this one

Here are some questions which can be solved using map . Please go through this link  if you hate Ramsay Bolton and enjoyed the Battle of Bastards :) 


Wednesday, 28 September 2016

2.) Stack

Hello guyz ,  this  time  I am writing about Stacks in c++

Stack is one  of  the data structures which is also a container of C++ stl .  
We all  have seen somewhat use of  stack in our day to day life . For more clarity , Let's assume there is a pile of plates in a party i.e one plate is on the  top of the other. If someone needs a plate , He removes the plate which is  on the top And if someone wants to add a plate in that pile He pus it on the top . So this is  a practical example of a stack.
Stack has the property of LIFO i.e the Last element is the First one to  come out as it was there in the previous example of  pile of the plates .

In programming word  -- Stack is an area of memory that holds all local variables and parameters used by any function, and remembers the order in which functions are called so that function returns occur correctly.
 Each time a function is called, its local variables and parameters are “”pushed onto”” the stack.
When the function returns, these locals and parameters are “”popped.””
Because of this, the size of a program’s stack fluctuates constantly as the program is running, but it has some maximum size.
A Stack has mainly two operations 1.)Push      2.)Pop

There are  many questions in competitive coding  where we need to implement Stack .

I will show the implementation of  stack in c++ stl . If you want to see the basic  coding  of implementing a stack ,, google it :) .

#include <iostream>      
#include <stack>          // we need  to implement the stack from stl library 
using namespace std;

int main ()
{
  stack<int> mystack;                    // you  can  store  any type of data 

  for (int i=0; i<5; ++i) 
{
       mystack.push(i);                     // push()   function puts data on the top of other in stack
}

cout << "Popping out elements...";
  while (!mystack.empty())                  //  returns true if  your stack is not empty
  {
     std::cout << ' ' << mystack.top();       // the top  value on the  stack  is accessed by .top() function
     mystack.pop();                                //  removes out the top value  present in the stack  thus making the next one element                                                              //the top one 
  }
  std::cout << '\n';

  return 0;
}

output :   4 3 2 1 0


If you want to practice questions regarding stack ,, google some of the tagged question  with stack .  while you  can try this one . This is a very good and easy  question regarding implementation  of stack  -  try this

Friday, 2 September 2016

Learning STL in C++ -- 1.) Pair

Hello friends
     These  days I spent  my time learning about STL (Standard Templae Library) in C++ .
Actually STL is  a software library in C++ .It has  mainly four components  namely , Algorithms , Functional , Containers , Iterators .
Out  of  which , I found  Algorithms  and Containers very useful and am still learning them.
C++ STL is very vast and very very  useful and  user friendly .

First of  All I  would  like  to tell you about Containers .
They are the Objects that store data. The standard Sequence  Containers include : Vector , Deque , Stack, List
The standard associative Containers are Set , Multiset , Map
There are  also other Containers like Pair , hash_set etc.

1.) Pair : It is a simple associative container  which can store two  types  of  data together . These two types  of  data are called as 'first' and 'second' respectively  .
To use pair and its methods we include utility library .

Here is an Example  showing basic  usage of pair in c++ :



#include <iostream>
#include <utility>
using namespace std;
int  main()
{
    int  n = 1;
    int a[5] = {1, 2, 3, 4, 5};

    // build a pair from two ints
    pair<int,int> p1 = std::make_pair(n, a[1]);
    std::cout << "The value of p1 is "
              << "(" << p1.first << ", " << p1.second << ")\n";
}
we can  use  any two  different  data types to  store in pair .

Pair has many uses in other containers , that i will explain later .

Meanwhile there is an important keyword named auto  in C++ 11 and onwards  Go through This link  to  know  about  it . Its very useful in certain cases .




Tuesday, 7 June 2016

JavaBIgInteger - A very important tool

Hello everybody !!
It has  been long  since  i  wrote something on my  blog .

I had  to take a gap due to my exams and vacations . This time i am gonna tell you about the benifits of Biginteger class of  java .
BigInteger class of java can be imported from math class of java . There are  several benifits of using BigInteger class which puts the java  user a way ahead  than C/c++ users in  certain aspects.
For Example : if  you are  required to find 25! ,,  there  are  no  any  built in data types in C/c++ which can store such a big value.
If you try finding 25! using C/C++ ,  it  would take you very complex method  to  do so . Fortunately we can solve it  easily in Java using BigInteger .

BigInteger class supports basic integer operations  in it . Some of the useful methods are :
addition : add(BI)  //BI-> BigInteger type
substraction : substract(BI)
multiplication : multiply(BI)
divide : divide(BI)
remainder : remainder(BI)
modular : mod(BI)

 javaBigInteger has several other  bonus features that can be useful during programming
contests—in terms of shortening the code length—compared to if we have to write these
functions ourselves. Java BigInteger class happens to have a built-in base number converter:
The class’s constructor and function toString(int radix), a very good (but probabilistic)
prime testing function isProbablePrime(int certainty), a GCD routine gcd(BI), and a
modular arithmetic function modPow(BI exponent, BI m)

the  following  program shows how to calculate 25! using BigInteger :

import java.util.*;
import java.math.*;

class Factorial{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n= 25,i,j,k;
BigInteger product = BigInteger.ONE;// BigInteger has special cnstants like ZERO,ONE,TEN etc
for(i=1;i<=n;i++)
{
product = product.multiply(BigInteger.valueOf(i)); // here we cant write i directly ,, coz integer needs to be typecasted in BigInteger here

}
System.out.println("The value of your faactorial is  = " + product);

}
}


Base number conversion using BigInteger :
given a base b and two  positive integers p and m in base b.We have to compute p%m in base b .
i.e if we have b=2 , p = 110 ,m = 011 .  answer should be 010 . i.e 5%3 = 2.
the following solution explains this :

class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
int b = sc.nextInt();
if (b == 0) break; // special class’s constructor!
BigInteger p = new BigInteger(sc.next(), b); // the second parameter
BigInteger m = new BigInteger(sc.next(), b); // is the base
System.out.println((p.mod(m)).toString(b)); // can output in any base
} } }

Tuesday, 29 March 2016

Modular Exponentiation

Yesterday i came through a question where , the user was asked to compute  modulus of exponential value of a number raised to power of a big number.  For example let , b =4,e=13, m =497.  we have  to  find c. where   c = (b^e)%m  .  obviously its time taking   to compute   (b^e).  
Here is the question :   question link
Note that b is only one digit in length and that e is only two digits in length, but the value be is 8 digits in length. i.e  be   =  67,108,864.   but  what happen  when ,, Consider b = 5 × 1076 and e = 17, both of which are perfectly reasonable values. In this example, b is 77 digits in length and e is 2 digits in length, but the value be is 1,304 decimal digits in length. Such calculations are possible on modern computers, but the sheer magnitude of such numbers causes the speed of calculations to slow considerably. 

 There are three methods  to compute this value :
1.) first one  is  the basic  one . i.e   calculate b^e and then take its modulus with m .

2.) Memory Efficient : this method requires much more operations than the previous method  but  it is much  better  and less time consuming  than  the previous one . The algorithm for the second one is 
if   c can be expressed as ,  c = a.b ,
 then :
c mod m = (a ⋅ b) mod m
c mod m = [(a mod m) ⋅ (b mod m)] mod m

The algorithm is as follows:
  1. Set c = 1e′ = 0.
  2. Increase e′ by 1.
  3. Set c = (b ⋅ c) mod m.
  4. If e′ < e, go to step 2. Else, c contains the correct solution to c ≡ be mod 'm.
Note that in every pass through step 3, the equation c ≡ be′ mod m holds true. When step 3 has been executed e times, then, c contains the answer that was sought. In summary, this algorithm basically counts up e′ by ones until e′ reaches e, doing a multiply by b and the modulo operation each time it adds one (to ensure the results stay small).
The example b = 4e = 13, and m = 497 is presented again. The algorithm passes through step 3 thirteen times:
  • e′ = 1. c = (1 ⋅ 4) mod 497 = 4 mod 497 = 4.
  • e′ = 2. c = (4 ⋅ 4) mod 497 = 16 mod 497 = 16.
  • e′ = 3. c = (16 ⋅ 4) mod 497 = 64 mod 497 = 64.
  • e′ = 4. c = (64 ⋅ 4) mod 497 = 256 mod 497 = 256.
  • e′ = 5. c = (256 ⋅ 4) mod 497 = 1024 mod 497 = 30.
  • e′ = 6. c = (30 ⋅ 4) mod 497 = 120 mod 497 = 120.
  • e′ = 7. c = (120 ⋅ 4) mod 497 = 480 mod 497 = 480.
  • e′ = 8. c = (480 ⋅ 4) mod 497 = 1920 mod 497 = 429.
  • e′ = 9. c = (429 ⋅ 4) mod 497 = 1716 mod 497 = 225.
  • e′ = 10. c = (225 ⋅ 4) mod 497 = 900 mod 497 = 403.
  • e′ = 11. c = (403 ⋅ 4) mod 497 = 1612 mod 497 = 121.
  • e′ = 12. c = (121 ⋅ 4) mod 497 = 484 mod 497 = 484.
  • e′ = 13. c = (484 ⋅ 4) mod 497 = 1936 mod 497 = 445.
The final answer for c is therefore 445, as in the first method.
Try  to  visualize the  solution  step by step on  your  own using the above algorithm .
The time taken  to compute this one  is much less as  compared to  the first method.

3.) Right to left binary method :
This method  is more efficient than above given  two methods as well  It is a combination of the previous method and a more general principle called exponentiation by squaring (also known as binary exponentiation). and the number of operations is equal to the number of digits in binary representation  of the exponential .
first of all convert  e  in binary form . i.e for e = 13 , its binary equivalent is 1101 . store this in an array . i.e arr[3] = 1 , arr[2] = 1 , arr[1] = 0, arr[0] = 1 .
The implementation of  this method is as  follows :
set, result=1, and base=b,j=0;  
    while(j<=size of array) 
    {
if(arr[j]==1)
    {
      result = (result * base) % m;
    }
j++;
        base = (base*base)% m;;
    }cout<<result<<endl;

Try  to implement  these methods on  your  own ,  because  that is  the only way  you are gonna learn  things . I am doing the same things ,  share  knowledge, it helps you to learn more and more :) keep coding