1005. Programming Pattern (35)解题报告
2017-01-14 22:26
288 查看
我运用基于哈希值的LCP算法解决了这道题。
这两种方法请参考《算法竞赛入门经典——训练指南(算法艺术与信息学竞赛)》3.4字符串(2)。
感谢神赐予我智慧和力量。
写这道题过程中也参考了以下两篇博文:
PAT (Top Level) Practise 1005 Programming Pattern (35)
1005. Programming Pattern (35)【待解决】
这两种方法请参考《算法竞赛入门经典——训练指南(算法艺术与信息学竞赛)》3.4字符串(2)。
感谢神赐予我智慧和力量。
写这道题过程中也参考了以下两篇博文:
PAT (Top Level) Practise 1005 Programming Pattern (35)
1005. Programming Pattern (35)【待解决】
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <queue> #include <vector> #include <stack> #include <algorithm> using namespace std; const int maxn = 1100000; const int x = 123; int n, m, pos, times; unsigned long long HASH[maxn], xp, hashn[maxn]; int r[maxn]; bool comp(const int &a, const int &b); void find(char str[]); int main(void) { char *str; setvbuf(stdin, new char[1 << 20], _IOFBF, 1 << 20); setvbuf(stdout, new char[1 << 20], _IOFBF, 1 << 20); scanf("%d", &n); str = new char[maxn]; getchar(); fgets(str, maxn, stdin); m = strlen(str); m--; str[m] = '\0'; HASH[m] = 0; int i; for (i = m - 1; i >= 0; i--) { HASH[i] = HASH[i + 1] * x + str[i]; } xp = 1; for (i = 0; i < n; i++) { xp *= x; } for (i = 0; i < m - n + 1; i++) { hashn[i] = HASH[i] - HASH[i + n] * xp; } find(str); for (i = 0; i < n; i++) { putchar(str[pos + i]); } putchar(' '); printf("%d", times); delete[] str; return 0; } bool comp(const int &a, const int &b) { return hashn[a] < hashn[b]; } void find(char str[]) { int i; for (i = 0; i < m - n + 1; i++) { r[i] = i; } sort(r, r + m - n + 1, comp); vector<int> substr; int cnt = 0; times = 0; for (i = 0; i < m - n; i++) { if (!i || hashn[r[i]] != hashn[r[i + 1]]) cnt = 1; if (hashn[r[i]] == hashn[r[i + 1]]) cnt++; if (cnt > times) { times = cnt; substr.clear(); substr.push_back(r[i]); } else if (cnt == times) { substr.push_back(r[i]); } } pos = substr[0]; for (i = 1; i < substr.size() - 1; i++) { if (strcmp(str + substr[i], str + substr[i + 1]) < 0) pos = substr[i]; } return; }
相关文章推荐
- 1012. Greedy Snake (35)解题报告
- RQNOJ 35 营救 解题报告
- 1013. Image Segmentation (35)解题报告
- 剑指Offer 面试题35:第一个只出现一次的字符 解题报告(华为OJ034-找出字符串中第一个只出现一次的字符)
- 1014. Circles of Friends (35)解题报告
- 1010. Lehmer Code (35)解题报告
- 1015. Letter-moving Game (35)解题报告
- 1016. Uniqueness of MST (35)解题报告
- 1017. The Best Peak Shape (35)解题报告
- 1002. Business (35)解题报告
- 1009. Triple Inversions (35)解题报告
- 1007. Red-black Tree (35)解题报告
- 1001. Battle Over Cities - Hard Version (35)解题报告
- 1004. To Buy or Not to Buy - Hard Version (35)解题报告
- 1008. Airline Routes (35)解题报告
- 1003. Universal Travel Sites (35)解题报告
- 1006. Tree Traversals - Hard Version (35)解题报告
- 1011. Cut Rectangles (35)解题报告
- [汇总]字符串题目推荐及解题报告
- hdu5755 2016 Multi-University Training Contest 3 Gambler Bo 解题报告