Find the Shortest Common Superstring(hdu1841,KMP)
2013-08-23 17:24
573 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1841
解析:
题意:
找到一个最短的串s,含有子串s1,s2
思路:两次KMP匹配
求出,s1后缀和s2前缀的最长公共串长度m1,
s2后缀和s1前缀的最长公共串长度m2;
ans=strlen(s1)+strlen(s2)-max(m1,m2);
6096 KB 359 ms C++ 956 B
*/
解析:
题意:
找到一个最短的串s,含有子串s1,s2
思路:两次KMP匹配
求出,s1后缀和s2前缀的最长公共串长度m1,
s2后缀和s1前缀的最长公共串长度m2;
ans=strlen(s1)+strlen(s2)-max(m1,m2);
6096 KB 359 ms C++ 956 B
*/
#include<stdio.h> #include<string.h> #include<iostream> using namespace std; const int maxn=1000000+10; char s1[maxn],s2[maxn]; int next[maxn]; int max(int a,int b) { return a>b? a:b; } void get_next(char s[]) { next[0]=-1; int j=-1; int i=0; while(s[i]!='\0') { if(j==-1||s[i]==s[j])//这里要注意一下 { i++; j++; if(s[i]!=s[j])next[i]=j; else next[i]=next[j]; } else j=next[j]; } } int KMP(char a[],char b[],int m1,int m2) { int j=0,i=0; get_next(a); while(i<m2&&j<m1) { if(j==-1||a[j]==b[i]) { i++; j++; } else j=next[j]; if(j==m1) return j; } return j; } int main() { int n,i,j; int len1,len2,ans; scanf("%d",&n); while(n--) { scanf("%s",s1); scanf("%s",s2); int t1,t2; len1=strlen(s1); len2=strlen(s2); t1=KMP(s1,s2,len1,len2); t2=KMP(s2,s1,len2,len1); ans=len1+len2-max(t1,t2); printf("%d\n",ans); } return 0; }
相关文章推荐
- hdu1841 Find the Shortest Common Superstring 两遍KMP
- hdu1841 Find the Shortest Common Superstring -- (KMP 前缀,后缀处理)
- 题目1841 Find the Shortest Common Superstring(KMP)
- HDU 1841 Find the Shortest Common Superstring(KMP 理解 应用 求组合串的next值判断是否匹配)
- HDU 1841 Find the Shortest Common Superstring(KMP)
- HDOJ 1841 Find the Shortest Common Superstring(KMP)
- HDU 1841 Find the Shortest Common Superstring(KMP灵活运用)
- 文章标题 HDU 1841:Find the Shortest Common Superstring(KMP)
- HDU 1841 Find the Shortest Common Superstring----KMP
- HDU1841 Find the Shortest Common Superstring (KMP两字符串的首尾连接)
- hdu1841 Find the Shortest Common Superstring
- hdu 1841 Find the Shortest Common Superstring
- hdu 1841 Find the Shortest Common Superstring
- HDU 1841: Find the Shortest Common Superstring
- HDU 1841 Find the Shortest Common Superstring
- HDU 1841 Find the Shortest Common Superstring
- hdu 1595 find the longest of the shortest
- HDU1595 find the longest of the shortest[最短路]
- hdu 1595 find the longest of the shortest(spfa)(存储并枚举最短路径的边)
- 杭电 1595 find the longest of the shortest Dijstra