[关闭]
@lawk97 2017-05-27T02:30:32.000000Z 字数 1787 阅读 1009

寒假专题训练--字符串

字符串


地址

B - Oulipo

[HDU - 168]

  1. #include <cstdio>
  2. #include <iostream>
  3. #include <cstring>
  4. #include <cmath>
  5. #include <algorithm>
  6. #include <string>
  7. #include <map>
  8. #include <stack>
  9. #include <queue>
  10. using namespace std;
  11. int t,ans,Next[10005];
  12. char w[10005],te[1000005];
  13. void getNext(){
  14. int len=strlen(w),j=0;
  15. Next[0]=Next[1]=0;
  16. for (int i = 1; i < len; ++i)
  17. {
  18. while(j>0&&w[i]!=w[j]){
  19. j=Next[j];
  20. }
  21. if (w[i]==w[j])
  22. {
  23. j++;
  24. }
  25. Next[i+1]=j;
  26. }
  27. }
  28. void search(){
  29. int j=0,lent=strlen(te),lenw=strlen(w);
  30. for (int i = 0; i < lent; ++i)
  31. {
  32. while(j>0&&te[i]!=w[j]){
  33. j=Next[j];
  34. }
  35. if (te[i]==w[j])
  36. {
  37. j++;
  38. }
  39. if (j==lenw)
  40. {
  41. ans++;
  42. j=Next[j];
  43. }
  44. }
  45. }
  46. int main(){
  47. scanf("%d",&t);
  48. while(t--){
  49. ans=0;
  50. scanf("%s%s",w,te);
  51. getNext();
  52. search();
  53. printf("%d\n",ans );
  54. }
  55. return 0;
  56. }

D - 统计难题

[HDU - 1251]

  1. #include <cstdio>
  2. #include <iostream>
  3. #include <cstring>
  4. #include <cmath>
  5. #include <algorithm>
  6. #include <string>
  7. #include <map>
  8. #include <stack>
  9. #include <queue>
  10. using namespace std;
  11. #define M 26
  12. int num;
  13. char t[15],w;
  14. struct tree{
  15. tree *next[M];
  16. int v;
  17. }*root;
  18. void create(char *str,int len){
  19. //int len=strlen(str);
  20. tree *p=root,*q=NULL;
  21. for (int i = 0; i < len; ++i)
  22. {
  23. int id=str[i]-'a';
  24. if (p->next[id]==NULL)
  25. {
  26. q=(tree *)malloc(sizeof(tree));
  27. for (int j = 0; j < M; ++j)
  28. {
  29. q->next[j]=NULL;
  30. }
  31. q->v=1;
  32. p->next[id]=q;
  33. p=p->next[id];
  34. }else{
  35. p=p->next[id];
  36. p->v++;
  37. }
  38. }
  39. //p-v=-1;
  40. }
  41. int search(char *str,int len){
  42. //int len=strlen(str);
  43. tree *p=root;
  44. for (int i = 0; i < len; ++i)
  45. {
  46. int id=str[i]-'a';
  47. p=p->next[id];
  48. if (p==NULL)
  49. {
  50. return 0;
  51. }
  52. }
  53. return p->v;
  54. }
  55. int main(){
  56. num=0;
  57. root=(tree *)malloc(sizeof(tree));
  58. for (int i = 0; i < M; ++i)
  59. {
  60. root->next[i]=NULL;
  61. }
  62. while(1){
  63. w=getchar();
  64. if (w=='\n')
  65. {
  66. create(t,num);
  67. num=0;
  68. w=getchar();
  69. if (w=='\n')
  70. {
  71. break;
  72. }
  73. }
  74. t[num++]=w;
  75. }
  76. num=0;
  77. while(~scanf("%c",&w)){
  78. if (w=='\n')
  79. {
  80. printf("%d\n",search(t,num));
  81. num=0;
  82. continue;
  83. }
  84. t[num++]=w;
  85. }
  86. return 0;
  87. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注