hdu 1686(Oulipo) KMP基础题 / hdu 2087(剪花布条)KMP基本运用

r囧r小猫 2021-12-11 11:32 282阅读 0赞

题目太长自己叙述吧!

原题链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1686

输入:t代表测试实例

第一行:模式串

第二行:匹配串

问模式串在匹配串中出现的次数。

3

BAPC

BAPC

AZA

AZAZAZA

VERDI

AVERDXIVYERDIAN

上面的三个实例的输出分别为:1 3 0

KMP算法看了有半天了吧!很朦胧啊!就霸王硬上弓了,套着模板A了这一题!

  1. 1 #include<iostream>
  2. 2 #include<cstring>
  3. 3 #include<cstdio>
  4. 4 using namespace std;
  5. 5 #define N 1000006
  6. 6 #define M 10004
  7. 7 char a[M];
  8. 8 char b[N];
  9. 9 int next[M];
  10. 10 int n,m;
  11. 11 void Get_next()
  12. 12 {
  13. 13 int i=0,j=-1;
  14. 14 next[0]=-1;
  15. 15 while(i<m)
  16. 16 {
  17. 17 if(j==-1||a[i]==a[j])
  18. 18 {
  19. 19 i++;
  20. 20 j++;
  21. 21 next[i]=j;
  22. 22 }
  23. 23 else
  24. 24 j=next[j];
  25. 25 }
  26. 26 }
  27. 27 int KMP()
  28. 28 {
  29. 29 int i=0,j=0;
  30. 30 int ans=0;
  31. 31 Get_next();
  32. 32 while(i<n&&j<m)
  33. 33 {
  34. 34 if(j==-1||b[i]==a[j])
  35. 35 {
  36. 36 i++;
  37. 37 j++;
  38. 38 }
  39. 39 else
  40. 40 j=next[j];
  41. 41 if(j==m)
  42. 42 ans++,j=next[j];
  43. 43 }
  44. 44 return ans;
  45. 45 }
  46. 46 int main()
  47. 47 {
  48. 48 int t;
  49. 49 cin>>t;
  50. 50 while(t--)
  51. 51 {
  52. 52 memset(next,-1,sizeof(next));
  53. 53 cin>>a;
  54. 54 m=strlen(a);
  55. 55 cin>>b;
  56. 56 n=strlen(b);
  57. 57 cout<<KMP()<<endl;
  58. 58 }
  59. 59 return 0;
  60. 60 }
  61. 61

hdu 2087 (剪花布条)KMP的基本运用

唯一需要注意的就是当模式串查找到后,j要回到0;

  1. 1 #include<iostream>
  2. 2 #include<cstring>
  3. 3 #include<cstdio>
  4. 4 using namespace std;
  5. 5 #define N 1005
  6. 6 char str[N],s[N];
  7. 7 int next[N];
  8. 8 int num;
  9. 9 void get_next()
  10. 10 {
  11. 11
  12. 12 int i=0,j=-1;
  13. 13 next[0]=-1;
  14. 14 int len=strlen(s);
  15. 15 while(i<len)
  16. 16 {
  17. 17
  18. 18 if(j==-1||s[i]==s[j])
  19. 19 {
  20. 20 i++;
  21. 21 j++;
  22. 22 next[i]=j;
  23. 23 }
  24. 24 else
  25. 25 j=next[j];
  26. 26 }
  27. 27 }
  28. 28 void KMP()
  29. 29 {
  30. 30
  31. 31 int i=0,j=0;
  32. 32 int len=strlen(str);
  33. 33 int len2=strlen(s);
  34. 34 while(i<len)
  35. 35 {
  36. 36 if(j==len2)
  37. 37 {
  38. 38 num++;
  39. 39 j=0;
  40. 40 }
  41. 41 if(j==-1||str[i]==s[j])
  42. 42 {
  43. 43 i++;
  44. 44 j++;
  45. 45
  46. 46 }
  47. 47 else
  48. 48 j=next[j];
  49. 49
  50. 50 }
  51. 51 if(j==len2)
  52. 52 num++;
  53. 53 }
  54. 54 int main()
  55. 55 {
  56. 56
  57. 57 while(scanf("%s",str)!=EOF)
  58. 58 {
  59. 59
  60. 60 if(str[0]=='#') break;
  61. 61 scanf("%s",s);
  62. 62 get_next();
  63. 63 num=0;
  64. 64 KMP();
  65. 65 printf("%d\n",num);
  66. 66
  67. 67
  68. 68 }
  69. 69 return 0;
  70. 70 }

转载于:https://www.cnblogs.com/heat-man/archive/2013/04/26/3044505.html

发表评论

表情:
评论列表 (有 0 条评论,282人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HDU 2087 花布 KMP入门

    Problem Description 一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条。计算一下能从花布条中尽可能剪出几块小饰