hdoj 1867 A + B for you again【kmp,前缀与后缀的匹配】
2016-03-23 21:07
567 查看
A + B for you again
Problem DescriptionGenerally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf”
and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.
Input
For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.
Output
Print the ultimate string by the book.
Sample Input
asdf sdfg asdf ghjk
Sample Output
asdfg asdfghjk
题目大意:输入两个字符串啊a和b,然后把两个字符串收尾相连,相连时候,把a的后缀和b的前缀重合【b的后缀和a的前缀重合】,还要求输出的合并字符串字典序最小且长度最短。
思路:首先比较两个字符串的长度,若一样长,则比较两个字符串的字典序,字典序小的放前面,
然后再计算a的后缀和b的前缀的匹配长度len1,接着计算b的后缀和a的前缀的匹配长度len2,如果len1<len2,则b在前,a在后;否则,a在前,b在后。
Accept代码【C++】【46MS】【2300K】
#include <cstdio> #include <cstring> using namespace std; char str_1[100001], str_2[100001]; int p[100001]; int total; void Kmp_huan(char *k, int len) { int i = 0, j = -1; p[0] = -1; while(i + 1 < len) { if(j == -1 || k[i] == k[j]) { i++, j++; if(k[i] == k[j]) p[i] = p[j]; else p[i] = j;//优化,即数据结构书中求的nextval数组【http://blog.csdn.net/nailnehc/article/details/49184599】 } else j = p[j]; } } int KMP(char *s, char *t, int len_s, int len_t) { int i = 0, j = 0; memset(p, 0, sizeof(p)); Kmp_huan(t, len_t); while(i < len_s){ while(s[i] != t[j]) { if(p[j] == -1) { j = 0; break; } j = p[j]; } if(s[i] == t[j]) j++; i++; } return j; } int main() { int x = 0, y = 0; int len_1, len_2; while(~scanf("%s %s", str_1, str_2)) {//笔者在这里吃了瘪,注意哈<--------- 看过来 本来是【while(1) { scanf()... }】Output Limit Exceeded len_1 = strlen(str_1); len_2 = strlen(str_2); x = KMP(str_1, str_2, len_1, len_2); y = KMP(str_2, str_1, len_2, len_1); if(x == y) { if(strcmp(str_1, str_2) > 0) { printf("%s", str_2); printf("%s\n", str_1 + y); } else { printf("%s", str_1); printf("%s\n", str_2 + y); } } else if(x > y){ printf("%s", str_1); printf("%s\n", str_2 + x); } else { printf("%s", str_2); printf("%s\n", str_1 + y); } } return 0; }
相关文章推荐
- 感动 Mr.Snail 作品集
- LeetCode OJ 217. Contains Duplicate
- 在rails中使用bcrypt进行密码的加密
- UVALive 7483 Air Conditioned Minions
- vector中插入pair
- INSTALL_PARSE_FAIL_NO_CERTIFICATE 打jar包的时候遇到的问题。
- leetcode 11. Container With Most Water
- HDU 2457:DNA repair
- 杭电1787GCD Again(欧拉函数)
- [Leetcode 265]Paint House II
- [Leetcode 256]Paint House
- [AI]根据葡萄特征聚类
- [AI](加入随机因素)局部搜索解决N皇后问题(含源码)
- BN: Accelerating Deep Network Training by Reducing Internal Covariate Shift
- IBM openblockchain学习(二)--chaincode源码分析
- public static void main(String args[]){ }中的String args[ ]
- Convention 插件学习
- PAT 1014 Waiting in Line (30)
- 海外投行抢滩大数据 人工智能等领域趋热
- python的smtplib发送email给多人要传列表而不是','.join(LIST)