Wednesday, 7 October 2015

Sliding Window Minimum Implementations

Sliding Window Minimum Implementations

Sliding window minimum is an interesting algorithm, so I thought I would implement it in a bunch of different languages. This repository contains (or will contain) implementations of the algorithm in different programming languages. What follows is an explanation of the problem and the algorithm.

Problem Introduction

The algorithm is sometimes also referred to as the Ascending Minima algorithm. I learnt the algorithm from a South African Computer Olympiad camp some years ago. I couldn't find any references to it in any journal, however there are some explanations on the Internet.
Given an array ARR and an integer K, the problem boils down to computing for each index i: min(ARR[i], ARR[i-1], ..., ARR[i-K+1]). The algorithm for this "slides" a "window" of size K over ARR computing at each step the current minimum. In other words the algorithm roughly follows this psuedocode:
for (i = 0; i < ARR.size(); i++) {
  remove ARR[i-K] from the sliding window
  insert ARR[i] into the sliding window
  output the smallest value in the window
}
The sliding window algorithm does the remove, insert and output step in amortized constant time. Or rather the time it takes to run the algorithm is O(ARR.size()).

Naive Algorithms

Before I explain the O(1) solution for sliding window minimum, let me explain some alternative solutions which are suboptimal. The most straight-forward solution is for each index i in ARR, simply loop over the values from ARR[i-K+1] to ARR[i] and keep track of the minimum:
void brute_force_time(std::vector<int> & ARR, int K) {
  for (int i = 0; i < ARR.size(); i++) {
     int min_value = ARR[i];
     for (int j = i - 1; j >= min(i - K + 1, 0); j--)
        min_value = min(min_value, ARR[j]);
     std::cout << min_value << ' ';
  }
}
The above C++ code runs in O(NK) where N = ARR.size(). We can improve on this by using a sorted set to speed up the minimum value queries to logarithmic time:
void logarithmic_time(std::vector<int> & ARR, int K) {
  std::multiset<int> window;
  for (int i = 0; i < ARR.size(); i++) {
     window.insert(ARR[i]);
     if (i - K >= 0)
       window.erase(window.find(ARR[i - K]));
     std::cout << *window.begin() << ' ';
  }
}
The window can have at most K elements, so the multiset insert, find and begin operations all take time O(logK). This gives us an overall time of O(NlogK).
We can improve the run-time by a constant factor by using a heap instead. All the heap operations (except finding the minima) have the same run-time complexity as the multiset versions, however heaps empirically perform better. We need to be able to remove arbitrary items in the heap, but the implementation of heaps in C++ (std::priority_queue) does not support this operation. Luckily a technique I have mastered in real life helps us get around this: we delete lazily. For each element in the priority queue we also store what index it was inserted from. Then when we query what the smallest element is, we discard it if its index falls out of range of our current window.:
void logarithmic_time2(std::vector<int> & ARR, int K) {
  // pair<int, int> represents the pair (-ARR[i], i). We use -ARR[i] since
  // priority_queue is by default a max-heap, but we want a min-heap. By
  // negating the value on insertion and removal we get a min-heap. One can
  // also use the rather ugly
  // std::priority_queue< std::pair<int, int>,
  //                      std::vector< std::pair<int, int> >,
  //                      std::greater< std::pair<int, int> > >

  std::priority_queue< std::pair<int, int> > window;
  for (int i = 0; i < ARR.size(); i++) {
     window.push(std::make_pair(-ARR[i], i));
     while(window.top().second <= i - K)
       window.pop();
     std::cout << (-window.top().first) << ' ';
  }
}
Note that deleting lazily can actually make this algorithm perform rather badly. If the input is N values from N to 1, then a value is never deleted from the priority queue leading to O(logN) insertions. However, on average this is empirically faster than the multiset version.

Sliding Window Minimum Algorithm

The idea of lazily deleting elements is a salient one, but by putting in a bit more effort when inserting an element into the window we can get amortized O(1) run-time. Say our window contains the elements {1, 6, 7, 2, 4, 2}. We want to add the element 5 to our window. Notice that all elements in the window greater than 5 will now never be the minimum in the window for future i values, so we might as well get rid of them. The trick to this is to store the numbers in a deque [1] and whenever inserting a number x we remove all numbers at the back of the deque which are greater than equal to x. Notice that if the deque was sorted before inserting, it will still be sorted after inserting x. Since the deque starts off sorted, it remains sorted throughout the sliding window algorithm. So the front of the deque will always be the smallest value.
The front of the queue might have a value which shouldn't be in the window anymore, but we can use the lazy delete idea with the deques as well. Now each element of ARR is inserted into the deque and deleted from the deque at most once. This gives as a total run-time of O(N) for the algorithm (amortized O(1) per insertion/deletion). Pretty sweet:
void sliding_window_minimum(std::vector<int> & ARR, int K) {
  // pair<int, int> represents the pair (ARR[i], i)
  std::deque< std::pair<int, int> > window;
  for (int i = 0; i < ARR.size(); i++) {
     while (!window.empty() && window.back().first >= ARR[i])
       window.pop_back();
     window.push_back(std::make_pair(ARR[i], i));

     while(window.front().second <= i - K)
       window.pop_front();

     std::cout << (window.front().first) << ' ';
  }
}

----------------------------------------implementation----------------------------

#include<iostream>
using namespace std;
  int arr[1000000];
  #include<bits/stdc++.h>
int main()
{
 int t;
     cin>>t;
     while(t--)
      {
       int n,k;
       cin>>n>>k;
       for(int i=1;i<=n;i++)
        {
         cin>>arr[i];
}
queue<pair<int,int> > q;


// note that queue will contains only nos in the increasing order  if any smaller
// no try to insert pop() , all biger number till rear

for(int i=1;i<=n;i++)
 {

  q.push(make_pair(arr[i],i));
 
  while(!q.empty())
    {
     if(q.front().first>arr[i] || q.front().second<i-k+1) q.pop();
     else break;
   }
   if(i>=k)// means than atleast k numbers are covered from array
  cout<<"till  "<<i<<" min "<<q.front().first<<endl;
 }
  }
}

Wednesday, 30 September 2015

optimal game stratgy

#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef long int li;

#define test()    int test_case;cin>>test_case;while(test_case--)
#define fr(i,n) for(int i=0;i<n;i++)
#define frr(i,a,n) for(int i=a;i<n;i++)
#define sll(a) scanf("%lld",&a)
#define sl(a) scanf("%ld",&a)
#define si(a) scanf("%i",&a)
#define sd(a)  scanf("%ld",&a)
#define sf(a) scanf("%f",&a)
#define rn(a) return a
#define pai pair<int,int>
#define pal pair<li,li>
#define pall pair<lli,lli>
#define ff first
#define ss second
#define mod  1000000007
#define mp make_pair
#define pb push_back
#define pll(a) printf("%lld\n",a);
#define pl(a) printf("%lld\n",a);
#define pi(a) printf("%d\n",a);
#define pd(a) printf("%lf\n",a);
#define pf(a) printf("%f\n",a);
lli  dp[3000][3000];
int solve(lli  arr[],int start,int end)
 {
   if(start>end)return 0;
  if(dp[start][end]!=-1)
 {

  return dp[start][end];
  }
  else if(start==end)
   {
 
    return dp[start][start];
   
  }
  else if(start+1==end)
   {

 
    return max(arr[start],arr[start+1]);
   
   }
 //  else if(dp[start][end]!=-1) return dp[start][end];
   else
   {
   
    lli val1=arr[start]+min(solve(arr,start+2,end),solve(arr,start+1,end-1));
     lli  val2=arr[end]+min(solve(arr,start,end-2),solve(arr,start+1,end-1));
   
     dp[start][end]=max(val1,val2);
   }
return dp[start][end];
 }
int main()
{

int n;
lli arr[10000];
int t=1;
while(1)
 {
    cin>>n;
   lli  tot_sum=0;
     if(n==0) return 0;
    
    
     else
     {
      for(int i=0;i<n;i++)
{
cin>>arr[i];
      tot_sum+=arr[i];
}
}
for(int i=0;i<n;i++)
 {
   for(int j=0;j<n;j++)
   dp[i][j]=-1;
 }
for(int i=0;i<n;i++) dp[i][i]=arr[i];

solve(arr,0,n-1);
 cout<<dp[0][n-1]<<endl;
 }
}

Friday, 25 September 2015

ncr using inverse modulo

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define ll long long int
#define mod 1000000007

ll powmod(ll a,ll b)
    {
    b=mod-2;
    ll result=1;
    while(b)
        {
        if(b&1)
            result=(result*a)%mod;
        b=b>>1;
        a=(a*a)%mod;
    }
    return result;
}
int main() {

    int t,n,m,i;
    ll fact[201];
    fact[0]=fact[1]=1;
    for(i=2;i<201;i++)
        fact[i]=(fact[i-1]*i)%mod;
    scanf("%i",&t);
    while(t--)
        {
        scanf("%i%i",&n,&m);
        ll ans=fact[n]*powmod((fact[m],mod);
        printf("%lli\n",ans%mod);
    }
    return 0;
}

Thursday, 17 September 2015

all destination shortest path using dijkestra and priority queue



#include <iostream>
using namespace std;
#include<bits/stdc++.h>
typedef long long int lli;
int visited[10010];
lli dist[10010];
#define pp pair<int,int>
// comparator for min heap
class Prioritize
{
public:
    int operator() ( const pair<int, int>& p1, const pair<int, int>& p2 )
    {
        return p1.second > p2.second;
    }
};

int main()
{
    int t;
     cin>>t;
      while(t--)
       {
        list<pair<lli,lli> >li[10010];
        lli n,m;
 
       cin>>n>>m;
       
          for(int i=0;i<m;i++)
           {
            lli a,b,c;
             cin>>a>>b>>c;
            li[a].push_back(make_pair(b,c));
            li[b].push_back(make_pair(a,c));
           
           }
         
             

            for(int i=1;i<=n;i++)
             {
              visited[i]=0;
              dist[i]=INT_MAX;
}


//  declaring pq;
            priority_queue<pp, vector<pp > , Prioritize > q;
           dist[1]=0;
       
           lli ans=0;
           int f=0;
           // need to find distance of all node from 1
           lli start=1;
           q.push(make_pair(1,0));
           while(!q.empty())
            {
           
   
            list<pair<lli,lli> > :: iterator it;
            lli start=q.top().first;
         
           
             q.pop();
            if(visited[start]==1) continue;
            visited[start]=1;
         
            for(it=li[start].begin();it!=li[start].end();it++)
             {
       
              if(!visited[it->first]  && dist[it->first]>dist[start]+it->second)
              {
             
               q.push(make_pair(it->first,dist[start]+it->second));
             
                dist[it->first]=dist[start]+it->second;
              }
             
             }
             
}
               

           
           for(int i=1;i<=n;i++) cout<<dist[i]<<" ";
         }
         return 0;
       }
     
     

Friday, 11 September 2015

INVERSION_COUNT

#include<iostream>
using namespace std;
 typedef long long int lli;
    lli temp[10000000];
      lli arr[1000000+10];
 #include<bits/stdc++.h>
 lli ic=0;
lli merge (lli arr[],lli start,lli mid,lli end)
   {
 
     lli i=start, j=mid+1;
     lli p=start;
   
      lli lc=0;
       while(i<=mid && j<=end)
        {
       
        if(arr[i]>arr[j])
        {
        lc+=mid-i+1;
        temp[p++]=arr[j];
        j++;
}
else
{
temp[p++]=arr[i++];
}
       
}
while(i<=mid) temp[p++]=arr[i++];
while(j<=end) temp[p++]=arr[j++];
for(int i=start;i<p;i++) arr[i]=temp[i];
return lc;
   }
 
 void  divide(lli arr[],lli start,lli end)
  {
 
  if(start<end)
  {
 
  lli mid=(start+end)/2;
 
  divide(arr,start,mid);
  divide(arr,mid+1,end);
  ic+=merge(arr,start,mid,end);
  }
 

  }
 
 int  main()
  {
  int t;
  cin>>t;
  while(t--)
   {
    ic=0;
    lli n;
    cin>>n;
 
    for(int i=0;i<n;i++)
     {
       cin>>arr[i];
       
 }
 divide(arr,0,n-1);
  cout<<ic<<endl;
}
return 0;
  }

Thursday, 9 July 2015

BINERY- EXPO

RECURSIVE IMPLEMENTATION:
int power(int x, unsigned int y)
{
    if( y == 0)
        return 1;
    else if (y%2 == 0)
        return power(x, y/2)*power(x, y/2);
    else
        return x*power(x, y/2)*power(x, y/2);
}

ITERATIVE IMPLEMENTATION:
1
2
3
4
5
6
7
8
9
10
11
12
long long int fastPower(long long base,long long power,long long M)
{
        long long result=1;
        while (power>0)
        {
                if (power%2==1)        
                        result = (result*base)%M;
                base = (base*base)%M;
                power/=2;
        }
        return result;
}