SRM 597 Div2 500

Problem Statement

 

Little Elephant from the Zoo of Lviv likes strings.

You are given a string A and a string B of the same length. In one turn Little Elephant can choose any character of A and move it to the beginning of the string (i.e., before the first character of A). Return the minimal number of turns needed to transform A into B. If it's impossible, return -1 instead.

Definition

 
Class: LittleElephantAndString
Method: getNumber
Parameters: string, string
Returns: int
Method signature: int getNumber(string A, string B)
(be sure your method is public)
 
 

Constraints

- A will contain between 1 and 50 characters, inclusive.
- B will contain between 1 and 50 characters, inclusive.
- A and B will be of the same length.
- A and B will consist of uppercase letters ('A'-'Z') only.

Examples

0)  
 
"ABC"
"CBA"
Returns: 2
The optimal solution is to make two turns. On the first turn, choose character 'B' and obtain string "BAC". On the second turn, choose character 'C' and obtain "CBA".
1)  
 
"A"
"B"
Returns: -1
In this case, it's impossible to transform A into B.
2)  
 
"AAABBB"
"BBBAAA"
Returns: 3
3)  
 
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBA"
Returns: 25
4)  
 
"A"
"A"
Returns: 0
5)  
 
"DCABA"
"DACBA"
Returns: 2


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class LittleElephantAndString {
public:
	int getNumber(string, string);
};

int LittleElephantAndString::getNumber(string A, string B) {
	int n=A.size();
	int c=0;
	int a[222];
	for(int i=0;i<222;i++)a[i]=0;
	for(int i=0;i<n;i++)
		a[A[i]]++,a[B[i]]--;
	for(int i='A';i<='Z';i++)if(a[i])return -1;
	for(int i=n-1,j=n-1;i>=0;i--)
	{
		if(A[i]==B[j])j--;
		else c++;
	}
	return c;
}

<%:testing-code%>
//Powered by [KawigiEdit] 2.0!


你可能感兴趣的:(tc,SRM)