题目:
链接:点击打开链接
题意:
找出两个字符串的后缀和前缀公共串,输出最短的串,并且为最小字典序。
算法:
KMP算法。
思路:
取最小字典序输出。。。
代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define MAXN 100010 char s1[MAXN],s2[MAXN]; int next[MAXN]; void get_nextval(char s[])//求next数组 { int i,j; i = -1; j = 0; next[0] = -1; int len = strlen(s); while(j<len) { if(i == -1 || s[i] == s[j]) { j++; i++; next[j] = i; } else i = next[i]; } } int KMP(char s1[],char s2[])//返回后缀和前缀的最大相同长度 { int i,j; i = 0; j = 0; get_nextval(s2); int len1 = strlen(s1),len2 = strlen(s2); while(i<len1 && j<len2) { if(j == -1 || s1[i] == s2[j]) { i++; j++; } else j = next[j]; } if(i == len1) { return j; } return 0; } int main() { //freopen("input.txt","r",stdin); int a,b; while(scanf("%s%s",s1,s2) != EOF) { a = KMP(s1,s2); b = KMP(s2,s1);//首先取最短的字符串输出,如果相同,比较字典序即可 if(a == b) { if(strcmp(s1,s2)>0) printf("%s%s\n",s2,s1+a); else printf("%s%s\n",s1,s2+a); } else if(a>b) { printf("%s%s\n",s1,s2+a); } else printf("%s%s\n",s2,s1+b); } return 0; }
hdu 1867 A + B for you again,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u013147615/article/details/25826929