UVa 12206 (字符串哈希) Stammering Aliens
2024-10-21 03:05:53
体验了一把字符串Hash的做法,感觉Hash这种人品算法好神奇。
也许这道题的正解是后缀数组,但Hash做法的优势就是编码复杂度大大降低。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int maxn = + ;
const int x = ;
int n, m, pos;
unsigned long long H[maxn], xp[maxn];
unsigned long long hash[maxn];
int rank[maxn];
char s[maxn]; bool cmp(const int& a, const int& b)
{ return hash[a] < hash[b] || (hash[a] == hash[b] && a < b); } bool possible(int L)
{
int cnt = ;
pos = -;
for(int i = ; i + L - < n; i++)
{
rank[i] = i;
hash[i] = H[i] - H[i + L] * xp[L];
}
sort(rank, rank + n - L + , cmp);
for(int i = ; i + L - < n; i++)
{
if(i == || hash[rank[i]] != hash[rank[i - ]]) cnt = ;
if(++cnt >= m) pos = max(pos, rank[i]);
}
return pos >= ;
} int main()
{
//freopen("in.txt", "r", stdin); xp[] = ;
for(int i = ; i < maxn; i++) xp[i] = xp[i - ] * x; while(scanf("%d", &m) == && m)
{
scanf("%s", s);
n = strlen(s);
H[n] = ;
for(int i = n - ; i >= ; i--) H[i] = H[i + ] * x + s[i] - 'a'; if(!possible()) puts("none");
else
{
int L = , R = n;
while(L < R)
{
int M = (L + R + ) / ;
if(possible(M)) L = M;
else R = M - ;
}
possible(L);
printf("%d %d\n", L, pos);
}
} return ;
}
代码君
最新文章
- iOS - .a静态库的打包(包括打包的文件中用到了一些别人的三方库和分类的处理)
- Javascript正则表达式匹配替换
- 20145225《Java程序设计》 第8周学习总结
- C#代码创建3D模型
- JDK安装 配置环境变量
- SQL语句查询所耗时间与效能的语句
- LCT模板
- C 实现的算法篇
- NOI2015考试小结
- Android使用Webview加载网页
- C#事件、委托简单示例
- python读写xml
- Swift - 程序进入后台,以及应用终止时调用的方法
- 基于visual Studio2013解决面试题之0309左移递减序列搜索
- T4模板合并js
- Optimizing Hive queries for ORC formatted tables
- 二叉查找树(Binary Search Tree)
- python类型错误:&#39;NoneType&#39; object is not subscriptable
- SQL查询日期格式化
- git概念及工作流程详解