hdu 1867 A + B for you again (kmp,最短的字符串a+b)
hdu 1867 题意 题意:给两个字符串,将两个字符串首尾拼接之后得到一个长度最短的字符串,求这个最短的字符串(一个串的前缀可能是另一个串的后缀,这样的话只出现一次就行了)
思路:kmp。。注意和hdu 1841区分。那道题是只要得到一个串包含两个串即可。这道题是首尾拼接得到。
还要注意。。这道题要求了长度相同时按照字典序小的方法拼接。。。
1/* ***********************************************
2Author :111qqz
3Created Time :2016年08月11日 星期四 05时08分32秒
4File Name :code/hdu/1867.cpp
5************************************************ */
6#include <cstdio>
7#include <cstring>
8#include <iostream>
9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <stack>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <deque>
19#include <ctime>
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E5+7;
34char a[N],b[N];
35int nxt[N];
36void getnxt( char *s)
37{
38 int n = strlen(s);
39 int i = 0 ;
40 int j = -1;
41 nxt[0] = -1;
42 while (i<n)
43 if (j==-1||s[i]==s[j]) nxt[++i] = ++j;
44 else j = nxt[j];
45}
46int kmp(char *a,char *b)
47{
48 int n = strlen(a);
49 int m = strlen(b);
50 int i = 0;
51 int j = 0;
52 getnxt(b);
53 while (i<n&&j<m)
54 {
55 if (j==-1||a[i]==b[j]) i++,j++;
56 else j = nxt[j];
57 }
58 if (i==n) //因为要保证,两个串是首尾拼接得到的,这样子必须是文本串的后缀和模式串的前缀相等。这是和hdu 1841的不同。
59 return j;
60 return 0;
61}
62int main()
63{
64 #ifndef ONLINE_JUDGE
65 freopen("code/in.txt","r",stdin);
66 #endif
67 while (scanf("%s\n%s",a,b)!=EOF)
68 {
69 int k1 = kmp(a,b);
70 int k2 = kmp(b,a);
71 // cout<<"k1:"<<k1<<" k2:"<<k2<<endl;
72 if (k1==k2)
73 {
74 if (strcmp(a,b)>0)
75 {
76 printf("%s",b);
77 printf("%s\n",a+k1);
78 }else
79 {
80 printf("%s",a);
81 printf("%s\n",b+k1);
82 }
83 }
84 else if (k1>k2)
85 {
86 printf("%s",a);
87 printf("%s\n",b+k1);
88 }
89 else
90 {
91 printf("%s",b);
92 printf("%s\n",a+k2);
93 }
94 }
95 #ifndef ONLINE_JUDGE
96 fclose(stdin);
97 #endif
98 return 0;
99}