TCS MockVita Solution : Problem A

Problem : Super ASCII String Cost

A string S is said to be "Super ASCII", if it contains the character frequency equal to their ascii values. String will contain only lower case alphabets ('a - z') and the ascii values will starts from 1 (i.e ascii value of 'a' is 1 and 'z' is 26). Now given a string S, you can perform operations, namely, add, delete and replace of any character present in the string. Every operation will consists of following costs
add = 2 unit
replace = 1 unit
delete = 3 unit

Your task is to convert the string to super ascii with the minimum cost. While converting the string to super ascii, the final string should contain the same characters as in the input string.




Input Format:
First line starts with T i.e. number of test cases, and then T lines will follow each containing a string "S".

Output Format:
Print the minimum cost of conversion for each string to a Super Ascii string.

Constraints:
1<=T<=100
1<=|S|<=300, S will contains only lower case alphabets ('a' - 'z').

Sample Input

aaab
aabbbc

Sample Output

4
2

Explanation:

For Case1:
Need to retain a, b since these are unique characters in this string
Some of possible ways are
1. Delete two a's and add one 'b'. Total cost = 8
2. Replace one a with b, and delete other 'a'. Total cost = 4.

For Case2:
Need to retain a, b, c since these are unique characters in this string
Some of possible ways are
1. Replace 'a' and 'b' with 'c'. Total cost = 2.
2. Delete one 'a' and one 'b' and then add two c's. Total cost = 10.

C++ Implementation:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <climits>
using namespace std;

int Cost(string s)
{
 int count[27];
 int cost = 0;
 int extras = 0;
 int replace = 0;
 memset(count,0,sizeof(count));
 for(int i=0;s[i]!='\0';i++)
 {
  count[s[i]-'a'+1]++;
 }
 
 for(int i=1;i<=26;i++)
 {
  if(count[i]!=0)
  {
   if((count[i]-i) < 0)
    replace = replace + (count[i]-i);
   extras = extras + (count[i]-i);
  }
 }
 
 if(extras==0)
  return abs(replace);
 else if(extras>0)
  return abs(replace) + (extras*3);
 else
  return (abs(replace)-abs(extras)) + abs(extras) * 2;
  //return abs(replace) + abs(extras)*2;
}

int main() {
 int t;
 cin>>t;
 while(t--)
 {
  string s;
  cin>>s;
  if(t>0)
      cout<<Cost(s)<<endl;
  else
      cout<<Cost(s);
 }
 return 0;
}
Other Problems from TCS Mockvita - 1 and Mockvita - 2:

Solution : MockVita-I Problem D

Solution : MockVita-II Problem C

Solution : MockVita-II Problem B

Solution : MockVita-II Problem D

Solution : MockVita-II Problem A

Solution : MockVita-I Problem B

Solution : MockVita-I Problem C

Solution : MockVita-I Problem F

Solution : MockVita-I Problem A