Linear Keyword

 

You are given a keyboard that consists of 26 keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.  You have to type the word s on this keyboard. It also consists only of lowercase Latin letters.  To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.  Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.  For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions 8, 5, 12 and 15, respectively. Therefore, it will take |5−8|+|12−5|+|12−12|+|15−12|=13 units of time to type the word "hello".  Determine how long it will take to print the word s.






OURSHOPKEEPER








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

int main()
{  
    int t;
    cin>>t;
    while(t--){
    string s, s2;
    int p, a[100], sum = 0;
   
        cin >> s;
       // gets(s);
        cin >> s2;
       
        int n = s.length();
        int count = 0;
        for (int i = 0; i < s.length(); i++)
        {
            for (int j = 0; j < s2.length(); j++)
            {
                if (s[i] == s2[j])
                {
           
                    p = i;
                    a[j] = p;
                   
                    count++;
                }
            }
        }
        int l = 0;
        //  -3  7  0 3
       
        for (int j = 0; j < count - 1; j++)
        {
           
            l = abs(a[j + 1] - a[j]);
            sum = sum + l;
           
        }
        cout << sum<<endl;
    }
}













    


Click on the above button to download the code.




Post a Comment

If you have furthur QUERIES please let us know

Previous Post Next Post