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 | ||||||||||||
|
| |||||||||||
| ||||||||||||
| ||||||||||||
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) | | |||||||||||
|
| |||||||||||
1) | | |||||||||||
|
| |||||||||||
2) | | |||||||||||
|
| |||||||||||
3) | | |||||||||||
|
| |||||||||||
4) | | |||||||||||
|
| |||||||||||
5) | | |||||||||||
|
|
类型:字符串 难度: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; } };
相关文章推荐
- 关于指针的一些事情
- 数据库链接字符串查询网站
- Flex字符串比较 还有Flex字符串操作
- ASP下经常用的字符串等函数参考资料
- 将字符串小写转大写并延时输出的批处理代码
- 将字符串转换成System.Drawing.Color类型的方法
- 字符串聚合函数(去除重复值)
- sqlserver中求字符串中汉字的个数的sql语句
- sql server字符串非空判断实现方法
- VBS的字符串及日期操作相关函数
- C#中字符串编码处理
- MySQL 字符串函数大全
- C/C++数据对齐详细解析
- C++中引用的使用总结
- C++中引用(&)的用法与应用实例分析
- 解析C++ 浮点数的格式化输出
- 深入分析C++中几个最不常用的关键字
- c++中inline的用法分析
- 深入解析C++ Data Member内存布局
- 从汇编看c++中默认构造函数的使用分析