string string string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 801 Accepted Submission(s): 232
Problem Description
Uncle Mao is a wonderful ACMER. One day he met an easy problem, but Uncle Mao was so lazy that he left the problem to you. I hope you can give him a solution.
Given a string s, we define a substring that happens exactly k times as an important string, and you need to find out how many substrings which are important strings.
Input
The first line contains an integer T (T≤100) implying the number of test cases.
For each test case, there are two lines:
the first line contains an integer k (k≥1) which is described above;
the second line contain a string s (length(s)≤105).
It’s guaranteed that ∑length(s)≤2∗106.
Output
For each test case, print the number of the important substrings in a line.
Sample Input
2
2
abcabc
3
abcabcabcabc
Sample Output
6
9
Source
2017 ACM/ICPC Asia Regional Shenyang Online
Recommend
越心急越容易读错题出不了题,太紧张了
连题都没读懂
是可重叠且必须只出现k次的
那么就好做了,就是必须在i 以下的k区间内呗,再减去相同的,就是上一块和下一块的最大值。
1的情况单独处理,也很好做啊。。。n-sa[i]-max(height[i],height[i+k)
啊啊啊啊啊,好烦啊。。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+500;
int t1[MAXN],t2[MAXN],c[MAXN];
typedef long long ll;
bool cmp(int *r,int a,int b,int l)
{
return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(char str[],int sa[],int ra[],int height[],int n,int m)
{
n++;
int i,j,p,*x=t1,*y=t2;
for(i=0;i<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[i]=str[i]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];
for(i=n-1;i>=0;i--) sa[--c[x[i]]]=i;
for(j=1;j<=n;j<<=1)
{
p=0;
for(i=n-j;i<n;i++) y[p++]=i;
for(i=0;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
for(i=0;i<m;i++) c[i]=0;
for(i=0;i<n;i++) c[x[y[i]]]++;
for(i=1;i<m;i++) c[i]+=c[i-1];
for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=1;x[sa[0]]=0;
for(i=1;i<n;i++)
x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
if(p>=n) break;
m=p;
}
int k=0;
n--;
for(i=0;i<=n;i++) ra[sa[i]]=i;
for(i=0;i<n;i++)
{
if(k) k--;
j=sa[ra[i]-1];
while(str[i+k]==str[j+k])k++;
height[ra[i]]=k;
}
}
int ra[MAXN],height[MAXN];
int sa[MAXN],num[MAXN];
char str[MAXN];
int ans[MAXN];
int ff[MAXN];
int mn[MAXN][21];
void ST(int n)
{
for(int i=1;i<=n;i++)
mn[i][0]=height[i];
for(int j=1;(1<<j)<=n;j++)
{
for(int i=1;i+(1<<j)-1<=n;i++)
{
mn[i][j]=min(mn[i][j-1],mn[i+(1<<(j-1))][j-1]);
}
}
}
int rmq(int i,int j)
{
int k=0;
while(1<<(k+1)<=(j-i+1)) k++;
return min(mn[i][k],mn[j-(1<<k)+1][k]);
}
int k;
ll solve(int x)
{
int tt=rmq(x+1,x+k-1);
tt-=max(height[x],height[x+k]);
return max(tt,0);
}
int main()
{
int t;
scanf("%d",&t);
int n;
while(t--)
{
scanf("%d",&k);
scanf(" %s",str);
int len=strlen(str);
str[len]=0;
memset(height,0,sizeof(height));
da(str,sa,ra,height,len,140);
n=len;
if(k==1)
{
ll res=0;
for(int i=1;i<=n;i++)
{
int vv=max(height[i],height[i+1]);
res+=max(0,n-sa[i]-vv);
}
printf("%lld\n",res );
continue;
}
ST(n);
ll res=0;
for(int i=1;i<=n-k+1;i++)
res+=solve(i);
printf("%lld\n",res );
}
return 0;
}