hdu 3336 Count the string (kmp + dp)
2016-05-12 19:01
507 查看
http://acm.hdu.edu.cn/showproblem.php?pid=3336
题意:给出一个长度为n的字符串,求出该字符串的所有前缀出现的总次数
思路:kmp求出该字符串的next数组,第i个位置dp[i]可有dp[next[i]]+1得到
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
#define N 1100000
#define met(a, b) memset(a, b, sizeof(a))
const double PI = acos(-1.0);
typedef long long LL;
char str
;
int Next
, dp
, len;
void Get_Next ()
{
int i = 0, j = -1;
Next[i] = j;
while (i<len)
{
if (j==-1 || str[i] == str[j])
Next[++i] = ++j;
else j = Next[j];
}
}
int main ()
{
int t, n;
scanf ("%d", &t);
while (t--)
{
met (str, 0);
met (dp, 0);
met (Next, 0);
scanf ("%d%s", &n, str);
len = strlen(str);
Get_Next ();
int ans = 0;
for (int i=1; i<=len; i++)
{
dp[i] = dp[ Next[i] ] + 1;
ans += dp[i];
ans %= 10007;
}
printf ("%d\n", ans);
}
return 0;
}
题意:给出一个长度为n的字符串,求出该字符串的所有前缀出现的总次数
思路:kmp求出该字符串的next数组,第i个位置dp[i]可有dp[next[i]]+1得到
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
#define N 1100000
#define met(a, b) memset(a, b, sizeof(a))
const double PI = acos(-1.0);
typedef long long LL;
char str
;
int Next
, dp
, len;
void Get_Next ()
{
int i = 0, j = -1;
Next[i] = j;
while (i<len)
{
if (j==-1 || str[i] == str[j])
Next[++i] = ++j;
else j = Next[j];
}
}
int main ()
{
int t, n;
scanf ("%d", &t);
while (t--)
{
met (str, 0);
met (dp, 0);
met (Next, 0);
scanf ("%d%s", &n, str);
len = strlen(str);
Get_Next ();
int ans = 0;
for (int i=1; i<=len; i++)
{
dp[i] = dp[ Next[i] ] + 1;
ans += dp[i];
ans %= 10007;
}
printf ("%d\n", ans);
}
return 0;
}
相关文章推荐
- bzoj 2124: 等差子序列 树状数组&hash
- POJ2484
- BZOJ4551 [Tjoi2016&Heoi2016]树
- 插入排序
- java中的网络通信
- c# 解析json 字符串 报异常 Bad JSON escape sequence 解决方案
- POJ 1129 Channel Allocation 请用爆搜
- DataNitro: 用Python高效处理Excel数据
- JAVA回调机制(CallBack)详解
- 论文阅读:Look-ahead before you leap: end-to-end active
- Android中SharedPreferences的使用
- JavaWeb操作Msql数据库显示数据流程(源代码+详细步骤)
- ios最简单的录音程序
- 八大排序之选择排序
- Go-Redis
- DB2数据库常用SQL命令学习总结汇总
- foreach循环
- 操作系统 实验三 进程调度模拟程序
- Leetcode数学类题目
- 【其他】大整数类Bignum