您的位置:首页 > 其它

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)【待解决】



#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: