Monday, December 10, 2012

Interesting Programming Problems

1.IOIPALIN (spoj, my code, level 2, original length - LCS of original and reversed string, bottom-up dp with space optimisation)

2.SAMER08D (spoj, my code, level 2, bottom-up DP)

3.COUNTARI (codechef, my code, solution is giving TLE but the solution implies a very strong concept which is worth learning)

4. SRM 549, Div 2, Level 2 (maximum bipartite matching, editorial)

5. SRM 338, Div 1, Level 3 (Game theory, editorialmy code)

6. FLIPCOIN (segment tree implementation with  lazy propogation, my code)

7. Given an array A of N integers such that each integer is less than equal to 29. Find the number of contiguous subsequences of integers such that xor of the integers in the subsequence is 0. Note that the subsequence can contain between 1 to N elements inclusive.
(solution- DP, Since the maximum value of integer is 29, there would be 32 xor values possible [0,31]. Suppose u know the number of subsequences whoes first element is A[i] and whoes xor value is X, then two cases arises- 1) the subsequence contains only A[i].     2)the subsequence contains A[i+1] also.Now assume we have already calculated number of subsequences starting with A[i+1] for each xor value, then we can simply find the answer for A[i],  pseudo code)

8. SRM 565, Div 1, Level 2 (Game theory, editorialmy code, idea in the above Q-7 is also used)

9. SRM 566, Div 2, Level 2 (Greedy approach, editorialmy code)

10. SRM 500, Div 2, Level 3(Maths, editorialmy code)

11. SRM 503, Div 2, Level 3 ( MST using Prim's, editorialmy code)

12.There is an array of 15 cards. Each card is putted face down on table. You have two queries:
 1. T i j (turn cards from index i to index j, include i-th and j-th card - card which was face down will be face up; card which was face up will be face down)
 2. Q i (answer 0 if i-th card is face down else answer 1)   (use BIT to solve ,my code)

13. HIGHWAYS (spoj, Dijkstra, my code)

14. SRM 570, Div 2, Level 3 (Finding the number of subtrees, editorialmy code)

15. SRM 571, Div 2, Level 3 (editorialmy code)

16. TASTR (codechef, suffix array for calculation of number of unique substrings of a string, editorial,my code)

Sunday, September 23, 2012

Never Give up !!!!




haste hue muskurate hue ghum raha tha mein,
laga sab kuch to mil gaya , masti mein jhum raha tha mein,
lekin hua jab duur is duniya ke jhoote dikhawo se,
kache rishto se, laalach ke chalawo se,
tab laga mere andar kuch to adhura h abhi,
kuch to hai jiski abhi bhi h mujhme kami,
kuch socha na samjha, bas chal pada kaato ki raho par,
mila dard hi dard jab pade paav in angaro par,
magar mile chahe kitna bhi dard,
nahi chorunga mein in raaho ko, lehro se bhari samundar ki in baho ko,
kyuki naseeb hote h sirf unhi gine chuno ko kinaare,
jo nirasha ke andhkaar se kabhi nahi h haare...........

keep going and never ever stop ...........

myself as Messi.......




college me mein engineer banne aaya tha,
bade bade sapno ko sach karne aaya tha,
lekin dekha jab use dimag ghum gaya,
padhai se dhyan hata dil jhum gaya,
lekin pata chala uska pehle se hi koi boyfriend tha,
jodi bhi achi thi dono ka pyaar bhi durust tha,
magar agar wo tha goal keeper to mein bhi ban gaya Lionel Messi,
aakhir kaise jane deta, ladki bhi thi kareena jaisi,
baad me pata chala ek nahi do nahi kaafi h uske liye excited,
ek akela Messi kya kare, samne h pura Manchester United............. ;-)... :P


Monday, September 17, 2012

Why use double pointer when adding node to Linked List?

Why use double pointer when adding node to Linked List? This question struck my mind when i first read about Linked Lists in my Second Semester. At that time i didnt gave it much thought. But from past 1 week i wanted the answer of this question. I googled it, but forums were full of nasty definitions of pointers and their usage, asked my seniours but they told me the bookish reasons which didnt made me satisfied, so i decided to do some experiments and make some conclusion......

OBSERVATION 1- If the linked list is not empty then we can add the nodes in it (obviously at the end) by using a single pointer only.

int insert(struct LinkedList *root, int item)
{
    struct LinkedList *temp;
    temp= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    temp->data=item;
    temp->next=NULL;
    struct LinkedList *p;
    p=root;
    while(p->next!=NULL)
    {
        p=p->next;
    }
    p->next=temp;
    return 0;
}


int main()
{
    int m;

    struct LinkedList *A;

    A=(struct LinkedList *)malloc(sizeof(struct LinkedList));
    //now we want to add one element to the list so that the list becomes non-empty
    A->data=5;
    A->next=NULL;
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}


Its simple to explain. We have a pointer in our main function which points to the first node (or root) of the list. In the insert() function we pass the address of the root node and using this address we reach the end of the list and add a node to it. So we can conclude that if we have address of a variable in a function (not the main function) we can make permanent changes in the value of that variable from that function which would reflect in the main function.



OBSERVATION 2- The above method of adding node failed when the list was empty.


int insert(struct LinkedList *root, int item)
{
    struct LinkedList *temp;
    temp= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    temp->data=item;
    temp->next=NULL;
    struct LinkedList *p;
    p=root;
    //check if list is empty
    if(p==NULL)
    {
        p=temp;
    }
    else
    {
      while(p->next!=NULL)
      {
          p=p->next;
      }
      p->next=temp;
    }
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;

    A=NULL;//initialise the list to be empty
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}


If you keep on adding elements and finally display the list then u would find that the list has undergone no changes and still it is empty.
The question which struck my mind was in this case also we are passing the address of the root node then why modifications are not happening as permanent modifications and list in the main function undergoes no changes. WHY? WHY? WHY? 
Then i observed one thing, when i write A=NULL the address of A becomes 0. This means now A is not pointing to any location in memory. So i removed the line
A=NULL; and made some modification in the insert function... 





some modifications......(below insert() function can add only one element to an empty list,, just wrote this function for testing purpose)




int insert(struct LinkedList *root, int item)
{
    root= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    root->data=item;
    root->next=NULL;
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}

the above method also fails because in the insert() function root stores same address as A in the main() function but after the line root= (struct LinkedList *)malloc(sizeof(struct LinkedList)); the address stored in root changes. Thus ,now , root (in insert() function) and A (in main() function)  store different addresses.

SO THE CORRECT FINAL PROGRAM WOULD BE...


int insert(struct LinkedList *root, int item)
{
    root->data=item;
    root->next=NULL;
    return 0;
}



int main()
{
    int m;

    struct LinkedList *A;
    A= (struct LinkedList *)malloc(sizeof(struct LinkedList));
    cout<<"enter the element to be inserted\n";
    cin>>m;
    insert(A,m);
    return 0;
}

But we dont want two different functions for insertion , one when list is empty and other when list is not empty. Now comes double pointer which makes things easy.

now pls give ur full attention,
lets see what double pointer can do,

ONE THING I NOTICED WHICH IS IMPORTANT IS THAT POINTERS STORE ADDRESS AND WHEN USED WITH '*' THEY GIVE VALUE AT THAT ADDRESS BUT POINTERS THEMSELVES HAVE THEIR OWN ADDRESS.
for example-
if we write int *a,p; a=&p; then *a would give value of p, a would give address of p, and &a would give address of pointer a.

now i would first give the complete program and then explain the concepts.....


int insert(struct LinkedList **root,int item)
{
    if(*root==NULL)
    {
        (*root)=(struct LinkedList *)malloc(sizeof(struct LinkedList));
        (*root)->data=item;
        (*root)->next=NULL;
    }
    else
    {
        struct LinkedList *temp=(struct LinkedList *)malloc(sizeof(struct LinkedList));
        temp->data=item;
        temp->next=NULL;
        struct LinkedList *p;
        p=*root;
        while(p->next!=NULL)
        {
            p=p->next;
        }
        p->next=temp;
    }
    return 0;
}


int main()
{
    int n,m;
    struct LinkedList *A=NULL;
    cout<<"enter the no of elements to be inserted\n";
    cin>>n;
    while(n--)
    {
        cin>>m;
        insert(&A,m);
    }
    display(A);
    return 0;
}



following are the observations->
1. root stores the address of pointer A (&A) , *root stores the address stored by pointer A and **root stores the value at address stored by A. In simple language root=&A, *root= A and **root= *A.
2. if we write *root= 1528 then it means that value at address stored in root becomes 1528 and since address stored in root is the address of pointer A (&A) thus now A=1528 (i.e. address stored in A is 1528) and this change is permanent.

 whenever we are changing value of *root we are indeed changing value at address stored in root and since root=&A ( address of pointer A)  we are indirectly changing value of A or address stored in A.

so now if A=NULL (list is empty) *root=NULL , thus we create the first node and store its address at *root  i.e. indirectly we storing the address of first node at A. If list is not empty , everything is same as done in previous functions using single pointer except we have changed root to *root since what was stored in root is now stored in *root.



Thursday, September 13, 2012

Kudiyo ke Nakhre.....




moh maaya me kyu phaste ho tum,
uski adaao pe kyu marte ho tum,
aamir khan ki kahi baat bhul gaye kya,
bus,train to thik h magar uske nakhro ko kyu sehan karte ho tum.

din raat padh kar bhi wo jitna nahi janti,
bina padhe usse jyada jaante ho

 tum,
khud ko bada creative samajhti h wo,
lekin innovation ke maamle me unke baap ho tum.

ek dusre ko saali , kutti , kamini bol kar
sochti h Oh my God aaj to kuch jyada hi bol diya,
unhe kya pata jo wo soch bhi nahi sakti
usse bhi achi gaaliyo ke inventor ho tum.

ghanto make up karke jitna chamakti h wo,
bina nahaye usse jyada chamakte ho tum,
8 ghante sone ke baad bhi kehti h i am sleepy,
3 ghanta so kar bhi padhai plus masti karte ho tum.

40 km/hr par scooty kya chala li,
khud ko samajhti h Rani Lakshmi Bai,
R.S. ke 2 pack aur sutta lagane ke baad bhi,
90 ki speed pe bike chalate ho tum.

2-4 comment kya maar diye,
bolti h wo tumko character less,
lekin train me waiting ticket me jab seat nahi milti,
to character less se unke best friend ban jaate ho tum.

moh maaya me kyu phaste ho tum,
uski adaao pe kyu marte ho tum,
aamir khan ki kahi baat bhul gaye kya,
bus,train to thik h magar uske nakhro ko kyu sehan karte ho tum.

Sunday, May 13, 2012

Still Suffering.....














socha tha 1st Year me kar lo thodi padhai,
 2nd year me to karna h bhot aaram,
magar kitni galat soch thi meri,
4th sem me ho gaya h jeena haraam.


kal tak sirf Counter Strike ke liye use kiya karte the computer ki hard disk aur RAM,
aaj usi computer pe compile karte h Heapsort aur Binary tree ke programs,
proxy banane ke alawa aur kuch bhi nahi aata tha,
ab Resume bhi likh lete h , A very big thanks to english waali maam,

padh padh kar Discrete Maths ke algebraic structure
ho gaye hum Total ghanchakkar,
padh kar computer ke bits and bytes,
badal gaya h dimag ka Memory Structure.


padh-padh kar Phonetics ban gaye hum total angrez,
hindi to bhul hi gaye h, chad gaya h videshi bhashao ka craze,

Recursive tree ke recursion ne , kar diya life ka destruction,
bolne ko kuch bacha nahi, But we are supporting Anna against corruption.

padh lo Cormen samaj me aa jayega Algorithm and Shortest path,
darne ki kya h baat jab tak uparwale ka h apne sir pe hath,
aur ho sakta h humari branch me bhi mass bunk,
bas mil jaye ek baar branch ke toppers ka sath,...............


Copyright © 2012 Piyush Golani All Rights Reserved

Saturday, May 12, 2012

The Facebook Fever


socha tha garmiyo ki chuttiyo me padhunga C++ ki book,
lekin subah hote hi computer par khul jata h facebook..
Notifications me hi duniya simat gayi h meri,
frustration mein i give myself a very dirty look...

koi likhta h LOVE is everything,
koi likhta h Love is fake,
aur koi likhta h Janu wapas aa jao,...
i wanna dive into your eyes.. coz ur eyes are much deeper than a lake...

dost hua from 'Single' to 'In a relationship'
aur likha 'I cant live without seing her face'..
2 weeks later back from 'In a relationship' to 'Single'
aur likha 'she took from me my freedom and space'...

jo bhi kaho Facebook made my mind fully paralysed and lame,
but still i get very happy when in the chat box ,
i see a green dot beside her name.. ;-)



Copyright © 2012 Piyush Golani All Rights Reserved

Getting started on Topcoder..


hey guys, this post is about how to get started on one of the biggest coding site Topcoder. You must have observed that this is not an ordinary coding site like codechef and codeforces where you can just open a problem and submit your solution. This is because of the following two reasons.....

1. Topcoder has a java applet called Arena on which you can write your code and after then compile and test your code against the various test cases.

2. Topcoder allows only Object-Oriented Languages like C++, Java, C99 etc . This means that if you are a C coder then you must shift to C++ in order to compete on topcoder.

Before beginning let me tell you that topcoder hosts a number of Algorithmic competitions and the most common among them are SRMs (Single Round Matches)...

Now do the following steps........

1. Open the Topcoder website.

2. Register yourself on the site. If you are already registered then simply click on the 'Go to Community Portal' link on the top-right of the page.

3. Now on the top-left corner of the new page you would observe a lot of symbols... Click on 'O(n)' symbol. when u place your mouse pointer on it you would see 'Algorithm Competitions' appearing below.

4. On the new window click on the red button which says 'Load Competition Arena'. A '.jnlp' file would be downloaded. Now Launch this Java file and after a few seconds you would notice a beautiful arena appearing on your screen..

5. Simply enter your Username and Password and click on the 'go' button. Now you are ready to code, practise and compete.  Below picture shows a view of the Arena after you login in.....


Now i would suggest you to observe the various functionalities of the Arena by clicking on various buttons..

Do write your comments below and dont forget to click on the 'g+' button if u liked the post.......

Senior hai Duffer...



pee rahi thi Maaza jab tum khadi sudha pe,

dekhkar upar kaha meine khuda se,

Oh my God banane me ise laga hoga aapko bhot time,

dekhkar adaye unki my heart feels so fine,

overflow karne laga tha mere dil ka buffer,


peeche se dost bola "Abe Senior h duffer",,,,,,,,,,,,,,


Copyright © 2012 Piyush Golani All Rights Reserved

Thursday, May 3, 2012

String to Int ----- Int to String (some functions and their uses)

In many programming problems the input is given in string format and we have to extract int values from that for our manipulation... also sometimes we have to output some int in the form of a string .... following are the methods by which this task can be accomplished.....

1. Conversion from string to int 
suppose we are given a string time= "20:12:33";
int hour,min,second;
sscanf(time.c_str(),"%d:%d:%d",&hour,&min,&second);
now after the execution of above statement ,
 hour= 20, min= 12, second= 33

2. Conversion from string to int (when string is a set of two or more space separated strings)
suppose we have a string info= "Alice 20 M 125";
the above string consists of three strings(space separated) "Alice" , "20", "M", "125"
firstly include a header file..... #include<sstream>
make a declaration in your code istringstream is(info);
the example is shown below.....
#include<iostream>
#include<sstream>

void demo(string info)
                                                               {
istringstream is(info);
string name;
int age , id;
char sex;
is>>name; // name= Alice
is>>age; // age=20
is>>sex; // sex= M
is>>id; //id= 125
                                                                }


3. Conversion from int to string 
include a header file #include<sstream>,
example is shown below.......
#include<iostream>
#include<sstream>

                                                            void demo()
                                                           {
int hh=10, mm= 9, ss= 23;
                                                            stringstream t;
                                                            string time;
                                                            t<<hh<<":"<<mm<<":"<<ss;
                                                            time= t.str();// time= "10:9:23"
                                                            }



4. snprintf() in c++
#include<iomanip>
int totalrank=5;
double total= 234;
string name= "Piyush";
char buf[150];
vector<string> ans;
ans.clear();
snprintf(buf , sizeof(buf) , "%s %d %0.1f", name.c_str() , totalrank , total);
ans.push_back(buf);
cout<<ans[0];
the output would be......
Piyush 5 234.0











Wednesday, January 4, 2012

a little fun with bits

you all have seen bits while reading something related to computers , specially in fields like computer architecture, etc but bits can serve us a great comfort in coding or solving medium or tough problems in computer languages like c or c++. so here we go....
suppose A=1100 ,B= 1010 then
A|B= 1110 (OR)
A&B= 1000 (AND)
A^B= 0110 (XOR- if there are odd number of 1s then 1 else 0)

x<<y means left shifting of bits of x by y or multiplication of x with 2^y
x>>y means right shifting of bits of x by y or division of x with 2^y

the most important use of shifting is to access a particular bit, for example 1<<x denotes x bit from the right set (1) and all other not set (0)



following are some operations on sets in terms of bits, (A=1100 B=1010, last item is absent in both , second last is present in B but absent in A and so on)

Set Union- A|B
Set Intersection- A&B
Set Negation(0 to 1 or 1 to 0)- ALL_BITS^A (where ALL_BITS is number with same number of bits as in A but all set (1) )



if we want to substract two numbers in  binary form then we instead perform a add operation ..... this is shown below
if A= 10101 and B= 11000 and we want to perform A-B then we would perform A+(-B), now in order to convert B to -B we have to take its two's complement as follows
B= 11000
B's one's complement= ~B= 00111
B's two's complement= ~B+1= 00111+00001= 01000
now simply A-B= A+(-B)= 10101+01000= 11101


Now suppose we want to find out the lowest bit in x which is set (1),,, by lowest we mean first encountered from the right hand side....
thus if x= 10100 and -1= 1111111 (in -1 all the bits are set, always)
x-1= x+(-1)= 10011
~(x-1)= 01100
x & ~(x-1)= 00100

thus to find the lowest bit which is set(1) perform x & ~(x-1)


to reverse the bits of an integer something not so simple has to performed...

x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);



bye bye :)




32-bit.........64-bit

This is the question which had been worrying me since a long time.... Whats the difference between a 32-bit and 64-bit Operating System. There are many and some are really difficult to understand unless u  are full equipped with full understanding of Computer Architecture and Organisation. But for a mere understanding,..... i am trying to explain. The total difference lies in the way memory is accessed. In earlier days , 4GB of RAM was more than sufficient for Personal Computers but with advancement of technology RAMs upto 16GB are available. Now suppose u have a computer running a 32-bit OS then u can have a RAM upto 4GB only. This is explained below-
2^32/(2^10 * 2^10 * 2^10)= 4GB
But suppose u fixed a RAM of 8GB on your computer, you have done a holly shit since your computer would be using only 4GB of it and rest 4GB went in vain. Thus in order to utilise the whole 8GB u should have a 64-bit OS on your computer.
2^64/(2^10 * 2^10 * 2^10)= 2^34GB
According to above calculation 64-bit OS can handle upto 2^34GB of RAM. But  this is practically impossible, so whats the upper bound on the size of RAM for 64-bit OS ? Hmm, at this moment i dont have the answer to this question,,,, :(

Now-a-days developers are focussing on developing 64-bit softwares and applications. Next i would be writing on running 32-bit apps on 64-bit or vice-versa. Till then gud bye... :-)

Some basic terms about Computer architecture

In this post am gonna write something about few very important terms about computer architecture,,,

according to speed we can say our list (in decreasing order of speed) consists of following:-
Registers
Cache Memory
Main Memory (RAM)


Registers- Processor registers or simply registers are located inside the processor. They typically hold a word of data which is of 32-bits or 64-bits. CPU instructs the Arithmetic and Logic Unit (ALU) to perform various operations on this data or with the help of it. They are the fastest of all forms of computer memories. CPU cannot process all the data and instructions at once and thus registers act as buffer and store all instructions at once and then CPU access these instructions from these registers at its speed.


Cache Memory-  it is the intermediate memory between the super fast registers and the relatively slow main memory. Its a very small capacity and high speed memory which acts as a buffer between the CPU and main memory. Actually access time of main memory is much more than accessing cache memory so whenever the CPU wants something , instead of directly going to the main memory it first searches the cache memory  and if it is not found there then it has to access main memory. Thus most frequently accessed instructions and data are put in the fast cache memory for speedy operations.

Main Memory- memory is nothing but RAM (Random Access Memory). Actually firstly i thought that it consists of both RAM and ROM but i was totally wrong. This memory is relatively costly, small sized and volatile (data is lost when computer is switched off).