HDU 4436 str2int (后缀自动机)
2024-10-19 12:41:25
把所有的字符串连接起来,中间用一个未出现的字符分隔开,题意是求这个串的所有子串(中间不含分隔符)形成的数之和。
把这个串加入SAM,对所有子串进行拓扑排序,从前往后统计。
记录到达这个节点的路径个数cnt,以及到达这个节点的总和sum。
设父节点是u,子节点是v
sum[v] = sum[u] * 10 + sum[v] + cnt[v]*j;
cnt[v] += cnt[u];
ans就是把所有的sum加起来。
注意:
1.忽略前导零
2.子串中不要含分隔符
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm> using namespace std; const int MAXN = ;
const int segma_size = ;
const int MOD = ; struct Suffix_Automaton
{
int F[MAXN << ]; //fail
int ant; //sum node
int last; //last point
int ch[MAXN << ][segma_size]; //side
int step[MAXN << ]; //len void init()
{
last = ant = ;
memset(F,,sizeof(F));
memset(ch,,sizeof(ch));
memset(step,,sizeof(step));
return;
} void ins( int x )
{
int t = ++ant, pa = last;
step[t] = step[last] + ;
last = t;
for( ; pa && !ch[pa][x]; pa = F[pa] )
ch[pa][x] = t;
if( pa == ) F[t] = ;
else if( step[pa] + == step[ ch[pa][x] ] )
F[t] = ch[pa][x];
else
{
int nq = ++ant, q = ch[pa][x];
memcpy( ch[nq], ch[q], sizeof(ch[nq]) );
step[nq] = step[pa] + ;
F[nq] = F[q];
F[q] = F[t] = nq;
for( ; pa && ch[pa][x] == q; pa = F[pa] )
ch[pa][x] = nq;
}
}
}; int N;
char str[MAXN + ];
int strL;
Suffix_Automaton SAM;
int r[MAXN << ];
int sum[MAXN << ];
int cnt[MAXN << ]; bool cmp( int a, int b )
{
return SAM.step[a] < SAM.step[b];
} void show()
{
for ( int i = ; i <= SAM.ant; ++i )
{
for ( int j = ; j < ; ++j )
{
printf( "%d ", SAM.ch[i][j] );
}
puts("");
}
return;
} int main()
{
//freopen( "s.txt", "w", stdout );
while ( scanf( "%d", &N ) == )
{
SAM.init();
strL = ;
for ( int n = ; n < N; ++n )
{
if ( strL )
str[strL++] = '' + ;
scanf( "%s", &str[strL] );
strL += strlen( &str[strL] );
}
for ( int i = ; i < strL; ++i )
SAM.ins( str[i] - '' ); for ( int i = ; i <= SAM.ant; ++i )
r[i] = i; sort( r + , r + + SAM.ant, cmp );
memset( sum, , sizeof(int)*(SAM.ant+) );
memset( cnt, , sizeof(int)*(SAM.ant+) ); int ans = ;
cnt[] = ;
for ( int i = ; i <= SAM.ant; ++i )
{
int u = r[i];
if ( i > && !cnt[u] ) continue;
ans = ( ans + sum[u] ) % MOD;
for ( int j = ; j < ; ++j )
{
if ( u == && j == ) continue;
if ( !SAM.ch[u][j] ) continue;
int v = SAM.ch[u][j];
sum[v] = ( sum[u] * + sum[v] + cnt[u] * j ) % MOD;
cnt[v] += cnt[u];
}
}
printf( "%d\n", ans ); }
return ;
}
最新文章
- OpenCASCADE Interpolations and Approximations
- 深入理解java内存模型系列文章
- SQL Server 收缩日志
- Unity3D IOS IPhone添加Admob的方法
- spring aop配置文档部分翻译
- 分布式存储Memcache替代Session方案
- c/c++中宏定义##连接符 和#符的使用
- The Accumulation of Capital
- sqlcmd的使用小结
- Servlet总结一
- vue的组件和生命周期
- Spark算子篇 --Spark算子之combineByKey详解
- tomcat查看端口被占用
- ZooKeeper leader election
- HTML之超链接
- 关于STL容器
- Curator的监听
- 2018ACM-ICPC南京区域赛---AJGIDKM
- Docker私有仓库介绍
- Python3实现生成验证码图片