Showing posts with label Programming and Algorithms. Show all posts
Showing posts with label Programming and Algorithms. Show all posts

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)

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.



Saturday, May 12, 2012

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.......

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