Friday, April 1, 2016

Array compression with map

problem link : http://www.shafaetsplanet.com/planetcoding/?p=1388

code:

#include<bits/stdc++.h>

using namespace std;

int main()
{
    map<long long int,long long int>mp;

    long long int a[1000];//given array
    long long int b[1000];//compressed/matched array

    long long  int d,c=0,i,j=0;
    long long  int n;
    cin>>n;//array size

    for(i=0; i<n; i++)
    {
        cin>>a[i];//taking array inputs
    }
    cout<<endl;
    for(i=0; i<n; i++)
    {
        d=a[i];
        if(mp.find(d)==mp.end())//checking if map with value d is empty or not
        {
            mp[d]=c;

            cout<<d <<" is matched with "<<c<<endl<<endl;
            c++;
        }
        d=mp[d];
        b[j]=d;
        j++;
    }
    cout<<endl;
    cout<<"compressed/matched array:"<<endl<<endl;
    for(i=0; i<n; i++)
    {
        cout<<b[i]<<" ";
    }
    cout<<endl;
    return 0;
}

No comments:

Post a Comment