Wednesday 18 January 2017

Longest Palindrome subsequences

Given a string S="abcdpcba".
The longest palindrome subsequences would be  "abcdcba".

Program:-

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
    string st;
    cin>>st;
    int arr[st.size()][st.size()]={0};
    for(int i=0;i<st.size();i++)
        arr[i][i]=1;
    int len=2;
    while(len<=st.size()){
        for(int i=0;i<st.size()-len+1;i++)
        {
           int j=i+len-1;
            if(st[i]==st[j])
                arr[i][j]=arr[i+1][j-1]+2;
            else arr[i][j]=max(arr[i][j-1],arr[i+1][j]);
        }
        len++;
    }
    cout<<arr[0][st.size()-1]<<endl;
    vector< vector<string> >res;
    res.resize( st.size() , vector<string>( st.size()) );
    for(int i=0;i<st.size();i++)
        res[i][i]=st[i];
     len=2;
    while(len<=st.size()){
        for(int i=0;i<st.size()-len+1;i++)
        {
           int j=i+len-1;
            if(st[i]==st[j] && len==2)
               { string temp;temp+=st[i];
                     temp+=st[j];
                res[i][j]=temp;}
            else if(st[i]==st[j])
                res[i][j]=st[i]+res[i+1][j-1]+st[j];
            else {
                if(res[i][j-1].size() >res[i+1][j].size())
                    res[i][j]=res[i][j-1];
                else res[i][j]=res[i+1][j];
            }       
}
        len++;
    }
    cout<<res[0][st.size()-1]<<"\n";

  return 0;

}

Friday 13 January 2017

HackeRank_weekofcode28_theValueofFriendship

#include <bits/stdc++.h>
using namespace std;


int main() {
    int test;
    cin>>test;
    while(test--){
       unsigned long long int sum=0,temper=0,valuer=1;
            int n,m;
            cin>>n>>m;
            vector<long int>vec[n];
            for(int i1=0;i1<m;i1++){
                int a,b;
                cin>>a>>b;
                a--;b--;
                vec[a].push_back(b);
                vec[b].push_back(a);
             }      
        vector<vector<long int> >result;
        vector<bool>visited(n,false);
        for(int i1=0;i1<n;i1++)
            if(visited[i1]==false)
            {
                vector<long int>temp;
                vector<int>dist(n,-1);
                dist[i1]=0;//starting number is always 0..
                queue<int>que;
                temp.push_back(i1);
                que.push(i1);//starting vertex....
                visited[i1]=true;
                while(!que.empty()){
                    int index=que.front();que.pop();
                    for(int i=0;i<vec[index].size();i++){
                        if(dist[vec[index][i]]==-1 ){
                            dist[vec[index][i]]=dist[index]+1;
                            que.push(vec[index][i]);
                            temp.push_back(vec[index][i]);
                            visited[vec[index][i]]=true;
                        }
                    }
                }
            result.push_back(temp);
          }
       
         pair<long int,long int>pr[result.size()];
        for(int i=0;i<result.size();i++){
           long int pp=0,qq=0,rr=0;
            for(int j=0;j<result[i].size();j++){
                pp+=vec[result[i][j]].size();
             //   cout<<result[i][j]<<" ";
            }
           // cout<<endl;
            pr[i] = make_pair(pp,result[i].size());
        }
        sort(pr,pr+result.size());
        reverse(pr,pr+result.size());
        for(int i=0;i<result.size();i++){
            pr[i].first = pr[i].first / 2;
            //cout<<pr[i].first<<" "<<pr[i].second<<endl;
        }
       unsigned long long int temp1=0,temp2=0,glb=0,gman=0,presum=0,cnt=0;
        for(int i=0;i<result.size();i++)
        {
            int flg=0;presum=0;
            if(pr[i].first>0)
            {
                sum+=(pr[i].second-1)*gman;
            }  
            for(int j=1;j<=pr[i].first;j++){
                if(j<pr[i].second){
                   sum+=(j+1)*(j);
                    presum=j*(j+1);
                }
                else {
                    cnt++;
                    //sum+=presum;
                 }
            }
            gman+=presum;
                //cout<<sum<<"\n";
        }
        sum+=cnt*gman;
     
        cout<<sum<<endl;
      }
    return 0;
}

Thursday 12 January 2017

Swapping 3 variable without extra variable

#include <bits/stdc++.h>
using namespace std;

int main() {
    int a,b,c;
    cin>>a>>b>>c;

    a=(a+c)-(c=a);
    b=(c+b)-(c=b);

    cout<<a<<" "<<b<<" "<<c;
    return 0;
}

Friday 6 January 2017

Euler's Totient Function

Euler’s Totient function Φ(n) for an input n is count of numbers in {1, 2, 3, …, n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1.

Program:-


#include <bits/stdc++.h>
using namespace std;

int Euler(int n){
    int result = n;
    for(int i=2;i*i<=n;i++){
        if(n%i == 0){
            while(n%i == 0) n = n/i;
            result = result - result/i;
        }
    }
    if(n>1) result = result - result/n;
    return result;
}

int main() {
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cout<<"Euler Totient of ";
        cout<<i<<" = "<<Euler(i)<<endl;
    }
    return 0;
}

Thursday 5 January 2017

Prime (SieveOfEratosthenes)

Program:-


#include <bits/stdc++.h>
using namespace std;

void SieveOfEratosthenes(int n)
{
    vector<bool>prime(n+1,true);
    for (int p=2; p*p<=n; p++)
    {
        if (prime[p] == true)
        {
            for (int i=p*2; i<=n; i += p)
                prime[i] = false;
        }
    }

    for (int p=2; p<=n; p++)
       if (prime[p])
          cout << p << " ";
}

int main()
{
    int n;
    cin>>n;
    SieveOfEratosthenes(n);
    return 0;

}

Project Euler #47: Distinct primes factors

Program:-

#include <bits/stdc++.h>
using namespace std;
 
void SieveOfEratosthenes(int n, int k,int m)
{
    vector<int>prime(n+1,0);
    for (int p=2; p<=n; p++)
    {
        if (prime[p] == 0)
        {
            for (int i=p*2; i<=n; i += p)
                prime[i]++;
        }
    }
    
    vector<int>vec;
    for (int p=2; p<=n; p++){
       if (prime[p]==k){ 
         if(vec.size()==0) {vec.push_back(p);}
           else if(vec[vec.size()-1]==p-1) vec.push_back(p);
               else {vec.resize(0);vec.push_back(p);}
       }
        if(vec.size()==k && vec[0]<=m){
            cout<<vec[0]<<endl;
            vec.erase(vec.begin(),vec.begin()+1);
        }
    }
}
 
int main()
{
    int n,k;
    cin>>n>>k;
    SieveOfEratosthenes(n+k+5,k,n);
    return 0;
}

Find the element that appears once (Bit Algorithms)

Example:-
input:- 12, 1, 12, 3, 12, 1, 1, 2, 3, 3
frequency:- 3
ans:- 2
Because other all number except 2 appears more than onces and same number of time. In this program k is other number frequency which are same for all the number except one number. 

Complexity:-
Expected time complexity is O(n) and O(1) extra space.

Program:-

#include <bits/stdc++.h>
using namespace std;

class bits{
    int max_size,n,k,result;
    public:
    int *arr;
    bits(int n1,int k1){
        max_size=32;
        k = k1;
        n=n1;
        result=0;
        arr = (int *)malloc(sizeof(int)*n1);
    }
    void input();
    void bitsnumber();
};

void bits::input(){
    for(int i=0;i<n;i++) cin>>arr[i];
}

void bits::bitsnumber(){
    int num,sum=0;
    for(int i=0;i<max_size ;i++){
        num=1<<i;
        sum=0;
        for(int j=0;j<n;j++)
            if(num & arr[j]) sum++;
            if(sum%k) result = result | num;
    }
    cout<<"The number which appears exactly one is: ";
    cout<<result<<endl;
}
int main()
{
    int n,k;
    cout<<"Enter the number of element 'n' and other number which frequency is exactly 'k' times\n";
    cin>>n>>k;
    cout<<"Enter n number\n";
    bits b(n,k);
    b.input();
    b.bitsnumber();
    return 0;
}

Longest Increasing Subsequence (Dynamic Programming)

Program:-

// Note: set(stl c++) don't use if the input are not distinct... 

#include <bits/stdc++.h>
using namespace std;

class Lis{
    int size;
    public:
    int *arr;
    Lis(int n){
        size=n;
        arr=(int *)malloc(sizeof(int)*n); 
//arr=new int(n);  See the miracle to uncomment it and comment malloc funtion;
    }
    void input();
    int Lislength();
};

void Lis::input(){
    for(int i=0;i<size;i++) cin>>arr[i];
}

int Lis::Lislength(){
    int j;
    vector<int>vec;
    vec.push_back(arr[0]);
    for(int i=1;i<size;i++)
    {
        for( j=0;j<vec.size();j++)
        {
            if(arr[i]<=vec[j])
            {
                vec[j]=arr[i];
                break;
            }
        }
        if(j==vec.size())
        vec.push_back(arr[i]);
    }
    return vec.size();
}

int main()
{
    int n;
    cin>>n;
    Lis lis(n);
    lis.input();
    cout<<lis.Lislength();
    return 0;
}

Wednesday 4 January 2017

Stack Data Structure Implementation using class in Cpp

Stack:-
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
  • Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  • Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
  • Peek: Get the topmost item.

Proram:-

#include <bits/stdc++.h>
using namespace std;
#define Capacity 50  //Capacity of stack;
class Stack{
    int top,capacity;
    int *arr;
    public:
    Stack(int size){
        arr = new int(size);
        top = -1;
        capacity=size;
    }
    bool isEmpty();
    bool isFull();
    void push(int );
    void pop();
    void print();
    int peek();   
};

bool Stack::isEmpty(){
    if(top==-1) {
      cout<<"stack is Empty\n"; 
      return true;
    }
    return false;
}

bool Stack::isFull(){
    if(top==capacity-1){
        cout<<"stack is Full\n";
        return true;
    }
    return false;
}

int Stack::peek(){
    if(isEmpty()) return -1;
    else return arr[top];
}

void Stack::push(int value){
    if(isFull()) return;
    cout<<"push the element "<<value<<endl;
    arr[++top]=value;
}

void Stack::pop(){
    if(isEmpty()) return;
    cout<<"pop element is: ";
    cout<<arr[top--]<<endl;
}

void Stack::print(){
  if(isEmpty()) return ;
  cout<<"stack element are: " <<endl;
  for(int i=0;i<=top;i++) cout<<arr[i]<<" ";
}
int main()
{
    Stack stack(Capacity);
    stack.pop();
    stack.push(1);
    stack.push(6);
    stack.push(4);
    stack.push(2);
    stack.push(7);
    cout<<"Top Element of stack is: "<<stack.peek()<<endl;
    stack.push(8);
    stack.pop();
    stack.print();
    return 0;
}

Heap Sort Implementation in Cpp

Heap Sort:-
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

Algorithm:- 
 
Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.

 Program:-

#include <bits/stdc++.h>
using namespace std;

void heapify(vector<int>&arr,int n,int i){
    int largest,l,r;
    largest=i;
    l=2*largest+1;
    r=2*largest+2;
    if(l<n && arr[l]>arr[largest]) largest=l;
    if(r<n && arr[r]>arr[largest]) largest=r;
    if(largest!=i){
        swap(arr[largest],arr[i]);
        heapify(arr,n,largest);
    }
}
   
void heapsort(vector<int>&arr,int n){
    for(int i=n/2-1;i>=0;i--){
        heapify(arr,n,i);
    }
    for(int i=n-1;i>0;i--){
        swap(arr[0],arr[i]);
        heapify(arr,i,0);
    }
}

void print(vector<int>&arr){
    for(int i=0;i<arr.size();i++) cout<<arr[i]<<" ";
}
int main()
{
    int n;
    cin>>n;
    vector<int>arr(n);
    for(int i=0;i<n;i++) cin>>arr[i];
    heapsort(arr,n);
    print(arr);
    return 0;
}

Power Funtion with Complexity (log(n))

Program:-

#include <bits/stdc++.h>
using namespace std;

#define P 1000000007

long long mypow(long long x,long long y) {
    long long R = 1;
    while (y) {
        if (y&1) {
            R = (R * x) % P;
        }
        y/=2;
        x = (x * x) % P;
    }
    return R;
}

int main() {
    long int a,b;
    cin>>a>>b;
    cout<<mypow(a,b);
    return 0;
}

Sorting of multiple number in structure of array in Cpp

 Program:-

#include <bits/stdc++.h>
using namespace std;
struct number{
    int a,b,c;
};
static bool comp(struct number aa, struct number ba){
    return aa.a<ba.a;
}

int main() {
    int n;
    cin>>n;
    struct number arr[n];
    for(int i=0;i<n;i++)
    {
      int a,b,c;
        cin>>a>>b>>c;
        arr[i].a=a;
        arr[i].b=b;
        arr[i].c=c;
    }  
    sort(arr,arr+n,comp);
    for(int i=0;i<n;i++)
        cout<<arr[i].a<<" "<<arr[i].b<<" "<<arr[i].c<<endl;
    return 0;
}

Cycle Detection in connected undirected graph using BFS (Implementation using STL Cpp)

Program:-

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n,m;
    cin>>n>>m;
    vector<int>vec[n];
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        a--;b--;
        vec[a].push_back(b);
        vec[b].push_back(a);
    }
    vector<int>dist(n,-1);
    dist[0]=0;//starting number is always 0..
    queue<int>que;
    que.push(0);
    while(!que.empty()){
        int index=que.front();que.pop();
        for(int i=0;i<vec[index].size();i++){
            if(dist[vec[index][i]]==-1){
                dist[vec[index][i]]=dist[index]+1;
                que.push(vec[index][i]);
            }
          
        }
    }
    if(n==1) cout<<"Not Cycle";
  
    for(int i=1;i<n;i++){
         set<int>st;
        for(int j=0;j<vec[i].size();j++)
            st.insert(dist[vec[i][j]]);
            st.insert(dist[i]);
        if(vec[i].size()>1 && st.size()<=vec[i].size()){ cout<<"Cycle";return 0;}
    }
    cout<<"Not Cycle";
   
    return 0;
}

Cycle Detection in directed graph using DFS (Implementation in STL Cpp)

Program:-

#include <bits/stdc++.h>
using namespace std;
int cycle=0;
void dfs(vector<int>*vec,vector<bool>&vis,int index,vector<bool>&visited){
    if(vis[index]==true) return;
    vis[index]=true;
    visited[index]=true;
    //cout<<index<<" ";
    for(int i=0;i<vec[index].size();i++){
        if(visited[vec[index][i]]) cycle=1;
        if(vis[vec[index][i]]==false){
            dfs(vec,vis,vec[index][i],visited);
        }
       
    }
}

int main() {
    int n,m;
    cin>>n>>m;
    vector<int>vec[n];
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        vec[a].push_back(b);
    }
    vector<bool>vis(n,false);
    for(int i=0;i<n;i++){
        if(vis[i]==false){
            vector<bool>visited(n,false);
            dfs(vec,vis,i,visited);
        }
    }
    if(cycle) cout<<"Cycle";
    else cout<<"Not Cycle";
    return 0;
}

BFS Implementation in cpp

Program:-

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n,m;
    cin>>n>>m;
    vector<int>vec[n];
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        a--;b--;
        vec[a].push_back(b);
        vec[b].push_back(a);
    }
    vector<int>dist(n,-1);
    dist[0]=0;//starting number is always 0..
    queue<int>que;
    que.push(0);
    while(!que.empty()){
        int index=que.front();que.pop();
        for(int i=0;i<vec[index].size();i++){
            if(dist[vec[index][i]]==-1){
                dist[vec[index][i]]=dist[index]+1;
                que.push(vec[index][i]);
            }
            /*if(dist[vec[index][i]]==dist[index]) {
                cout<<"Biparite Graph\n";
                return 0;
            }*/
        }
    }
    cout<<"Distance from starting vertex\n";
    for(int i=0;i<n;i++) cout<<dist[i]<<" ";
    return 0;
}

DFS Implementation in cpp

 //Program:-

#include <bits/stdc++.h>

using namespace std;
void dfs(vector<int>*vec,vector<bool>&vis,int index){
    if(vis[index]==true) return;
    vis[index]=true;
    cout<<index<<" ";
    for(int i=0;i<vec[index].size();i++){
        if(vis[vec[index][i]]==false){
            dfs(vec,vis,vec[index][i]);
        }
    }
}

int main() {
    int n,m;
    cin>>n>>m;
    vector<int>vec[n];
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        vec[a].push_back(b);
        vec[b].push_back(a);
    }
    vector<bool>vis(n,false);
    for(int i=0;i<n;i++){
        if(vis[i]==false){
            dfs(vec,vis,i);
            cout<<endl;
        }
    }
   
    return 0;
}

Monday 2 January 2017

Linked list implementation using class in cpp

//linked list implementation using class in c++.
#include <bits/stdc++.h>
using namespace std;
class node{
    friend class linked;
    int data;
    public:
    node *next;
    node(){
        data=0;
        next=NULL;
    }
};
class linked{   
    public:
    node *start=NULL;
    node *temp=NULL;
    node *head;
    void insert(int item);
    void print();
};
void linked::insert(int data){
    head = new node();
    head->data=data;
    if(start == NULL){
        start=head;
        temp=head;
        start->next=NULL;
    }
    else{
        while(temp->next!=NULL){
            temp=temp->next;
        }
        temp->next=head;
        head->next=NULL;
    }
}
void linked::print(){
    node *head=start;
    while(head){
        cout<<head->data<<endl;
        head=head->next;
    }
}
int main() {
   linked list;
    for(int i=1;i<11;i++)
        list.insert(i);
    list.print();
    return 0;
}