Header Ad

HackerEarth Fast Sort problem solution

In this HackerEarth Fast Sort problem solution From the childhood, we are taught that a comes before b then b comes before c and so on.So whenever we try to sort any given string we sort it in that manner only placing a before b and so on.But what happens if we initially change the pattern of sorting .This question arrived in Arav's young mind. He thought what would the final string be like if z comes before a and a comes after c and so on. He got really puzzled in finding out the final sorted string.So he asks you for help.

He gives you two strings.One the pattern string P which decides the order of alphabets and the second that is the final string F which needs to be sorted. Help him by telling him the final sorted string.


HackerEarth Fast Sort problem solution


HackerEarth Fast Sort problem solution.

#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(false);cin.tie(0);
using namespace std;
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define mp make_pair
#define all(a) a.begin(),a.end()
#define bitcnt(x) __builtin_popcountll(x)
#define MOD 1000000000
#define MAXN 500005
typedef unsigned long long int uint64;
typedef long long int int64;


int cnt[26];
string s,pat;
int main(){
int t,i;
cin>>t;
while(t--){
cin>>pat>>s;
for(i=0;i<26;i++)
cnt[i]=0;
for(i=0;i<s.length();i++)
cnt[s[i]-'a']++;
for(i=0;i<pat.length();i++){
while(cnt[pat[i]-'a']--){
printf("%c",pat[i]);
}
}
printf("\n");
}
return 0;
}

Second solution

#include<bits/stdc++.h>

using namespace std;

#define vi vector < int >
#define pii pair < int , int >
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define foreach(it,v) for( __typeof((v).begin())it = (v).begin() ; it != (v).end() ; it++ )
#define ll long long
#define llu unsigned long long
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define dbg(x) { cout<< #x << ": " << (x) << endl; }
#define dbg2(x,y) { cout<< #x << ": " << (x) << " , " << #y << ": " << (y) << endl; }
#define all(x) x.begin(),x.end()
#define mset(x,v) memset(x, v, sizeof(x))
#define sz(x) (int)x.size()

char p[26],f[10005];
int pos[26];

bool cmp(char a,char b)
{
return pos[a-'a'] < pos[b-'a'];
}

int main()
{
int t;
scanf("%d",&t);
assert(1 <= t && t <= 10);
while(t--)
{
scanf("%s",p);
scanf("%s",f);
int n,i;
for(i=0;p[i];i++)
{
assert('a' <= p[i] && p[i] <= 'z');
pos[p[i]-'a'] = i;
}
for(i=0;f[i];i++)
{
assert('a' <= f[i] && f[i] <= 'z');
}
n = i;
assert(1 <= n && n <= 100000);
sort(f,f+n,cmp);
printf("%s\n",f);
}
return 0;
}

Post a Comment

0 Comments