TopCoder SRM 597 Div1 第1题


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 ofA and move it to the beginning of the string (i.e., before the first character ofA). 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

 

类型:字符串  难度:2.5

题意:给出A,B两个字符串,长度相同,允许对A做一种操作:将A中任意位置字符放到第一个位置,问对A做几次这个操作,A和B相同,若不可能,返回-1。

分析:最长公共子序列的变形问题,dp解决即可。即从A的尾部反向遍历,dp[i]表示从A末尾到第i个位置 与 B从末尾开始匹配的最大长度,A匹配字符可以不连续,B匹配字符位置连续,且必须从末尾开始匹配,即A[m]=B[n],i<m<len(A),n=j,j+1,...,len(B)。

递推方程:dp[i] = max(dp[j]+1),i<j<len(A),A[i]==B[len(B)-dp[j]-1]

答案就是len(A)减去最大匹配长度。

代码:

#include<string>
#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
using namespace std;

class LittleElephantAndString
{ 	 
	public:
		int getNumber(string A, string B)
		{
			int la = A.length();
			int cnt[30];
			memset(cnt,0,sizeof(cnt));
			
			for(int i=0; i<la; i++)
			{
				cnt[A[i]-'A']++;
				cnt[B[i]-'A']--;
			}
			for(int i=0; i<26; i++)
				if(cnt[i]!=0) return -1;
			
			int dp[60],ans = 0;
			memset(dp,0,sizeof(dp));
			
			if(A[la-1] == B[la-1]) 
			{
				dp[la-1] = 1;
				ans = 1;
			}
			else dp[la-1] = 0;
			
			
			for(int i=la-2; i>=0; i--)
			{
				for(int j=la-1; j>i; j--)
				{
					int tmp;
					if(A[i] == B[la-dp[j]-1])
						tmp = dp[j]+1;
					else
						tmp = 0;
					if(tmp > dp[i]) dp[i] = tmp;
					if(tmp > ans) ans = tmp;
				}
			}
			return la-ans;
		}
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值