hdu 1867 A+B again for you

本文介绍了一个基于KMP算法解决特定字符串处理问题的方法。通过实现next数组优化字符串匹配过程,解决了两个字符串相加时如何避免重复子串的问题。文章提供了一个完整的C++代码示例,并附带了解题思路。

A + B for you again

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9291    Accepted Submission(s): 2274


Problem Description
Generally 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
 
简单的应用kmp以及next数组。。
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <string.h>
 4 #include <string> 
 5 #include <map>
 6 #include <queue>
 7 #include <deque>
 8 #include <vector>
 9 #include <set>
10 #include <algorithm>
11 #include <math.h>
12 #include <cmath>
13 #include <stack>
14 #include <iomanip>
15 #define mem0(s1) memset(s1,0,sizeof(s1))
16 #define meminf(s1) memset(s1,0x3f,sizeof(s1))
17 #define ll long long
18 using namespace std;
19 int nex[1000005],l1,l2;
20 void getn(int n,char c[])
21 {
22     int i=0,j=-1;
23     nex[0]=-1;
24     while(i<n)
25     {
26         if(j==-1||c[i]==c[j])
27         {
28             i++;j++;nex[i]=j;
29         }
30         else j=nex[j];
31     }
32     return;
33 }
34 int kmp(char s1[],char s2[])
35 {
36     int i,j=0,n,m;
37     n=strlen(s1);
38     m=strlen(s2);
39     getn(m,s2);
40     for(i=0;i<n;i++)
41     {
42         while(j&&s1[i]!=s2[j])j=nex[j];
43         if(s1[i]==s2[j])j++;
44     }
45     return j;
46 }
47 int main()
48 {
49     char s1[100005],s2[100005];
50     wshile(~scanf("%s%s",s1,s2))
51     {
52         l1=strlen(s1);l2=strlen(s2);
53         int h=kmp(s1,s2);
54         int hh=kmp(s2,s1);
55         if(h>hh||(h==hh&&strcmp(s1,s2)<0)) printf("%s%s\n",s1,s2+h);
56         else printf("%s%s\n",s2,s1+hh);
57     }
58     return 0;
59 }
View Code

 

转载于:https://www.cnblogs.com/TYH-TYH/p/9382071.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值