当前位置:   article > 正文

保研机试 数据结构问题总结_数据结构机试题目

数据结构机试题目

一、字典树

1、统计难题 HDU - 1251 

思路:

直接建一棵字典树,在建树的过程中,统计前缀出现的次数。那么我们就可以直接在查询时查到一个字符串的最后一个字符对应位置的sum值。

代码:

  1. #include<iostream>
  2. #include<algorithm>
  3. #define rep(i,a,b) for(int i=a;i<=b;i++)
  4. #define dep(i,a,b) for(int i=a;i>=b;i--)
  5. #define ll long long
  6. #include<string.h>
  7. #include<queue>
  8. #include<stack>
  9. #include<cstdio>
  10. #include<cmath>
  11. #include <stdlib.h>
  12. #include<stack>
  13. using namespace std;
  14. const int maxn=1000000+10;
  15. #define mod 1000000007
  16. #define INF 0x3f3f3f3f
  17. int dx[]= {-1,1,0,0};
  18. int dy[]= {0,0,-1,1};
  19. int n,k;
  20. char ch[20];
  21. int trie[maxn][30];
  22. int sum[maxn];
  23. int cnt;
  24. void inserts()
  25. {
  26. int s=0;
  27. for(int i=0;ch[i];i++)
  28. {
  29. int v=ch[i]-'a';
  30. if(trie[s][v]==0)
  31. {
  32. trie[s][v]=cnt++;
  33. }
  34. s=trie[s][v];
  35. sum[s]++;
  36. }
  37. }
  38. int finds()
  39. {
  40. int s=0;
  41. for(int i=0;ch[i];i++)
  42. {
  43. int v=ch[i]-'a';
  44. if(trie[s][v]==0)
  45. {
  46. return 0;
  47. }
  48. s=trie[s][v];
  49. }
  50. return sum[s];
  51. }
  52. int main()
  53. {
  54. cnt=1;
  55. while(gets(ch)&&ch[0]!=NULL)
  56. {
  57. inserts();
  58. }
  59. while(gets(ch))
  60. {
  61. int ans=finds();
  62. printf("%d\n",ans);
  63. }
  64. return 0;
  65. }

二、尺取法

1、三数之和

https://leetcode-cn.com/problems/3sum/

2、四数之和

https://leetcode-cn.com/problems/4sum/

三、前缀和后缀

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/955472
推荐阅读
相关标签
  

闽ICP备14008679号