P - 剪花布条

柔光的暖阳◎ 2022-03-21 13:28 164阅读 0赞

题目描述:

一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
Input
输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。
Output
输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。
Sample Input
abcde a3
aaaaaa aa

#

Sample Output
0
3
分析:熟悉了KMP,一眼就能看出这又是一个KMP匹配题。不过在匹配的时候有一点点小的差异。具体见代码

  1. #include"stdio.h"
  2. #include"string.h"
  3. void Get_next(char text[],int next[])
  4. {
  5. int i,j;
  6. int len=strlen(text);
  7. next[0]=-1;
  8. i=0;j=-1;
  9. while(i<len)
  10. {
  11. if(j==-1||text[i]==text[j])
  12. {
  13. i++;j++;
  14. if(text[i]==text[j])
  15. next[i]=next[j];
  16. else
  17. next[i]=j;
  18. }
  19. else
  20. j=next[j];
  21. }
  22. }
  23. int Index_KMP(char text[],int next[],char word[])
  24. {
  25. int i,j,k;
  26. int lentext=strlen(text);
  27. int lenword=strlen(word);
  28. int count=0;
  29. i=0;j=0;
  30. while(i<lentext)
  31. {
  32. while(j<lenword&&i<lentext)
  33. {
  34. if(j==-1||text[i]==word[j])
  35. {
  36. i++;j++;
  37. }
  38. else
  39. {
  40. j=next[j];
  41. }
  42. if(j==lenword)//这里是匹配成功了
  43. {
  44. count++;//数量加1
  45. j=0;//重新从0开始匹配,因为i并未到达尽头
  46. }
  47. }
  48. }
  49. return count;
  50. }
  51. int main()
  52. {
  53. char text[1001],word[1001];
  54. int next[1001];
  55. int i,j,count;
  56. while(~scanf("%s",text))
  57. {
  58. if(text[0]=='#')
  59. break;
  60. scanf("%s",word);
  61. Get_next(word,next);
  62. count=Index_KMP(text,next,word);
  63. printf("%d\n",count);
  64. }
  65. }

发表评论

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

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

相关阅读