您的位置:首页 > 运维架构

TopCoder SRM 597 Div1 第1题

2013-11-25 23:33 375 查看
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
,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;
}
};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TopCoder C++ 字符串