每个 UCloud 用户会构造一个由数字序列组成的秘钥,用于对服务器进行各种操作。作为一家安全可信的云计算平台,秘钥的安全性至关重要。因此,UCloud 每年会对用户的秘钥进行安全性评估,具体的评估方法如下:
首先,定义两个由数字序列组成的秘钥 a 和 b 近似匹配(≈) 的关系。a 和 b 近似匹配当且仅当同时满足以下两个条件:
- ∣a∣=∣b∣,即 a 串和 b 串长度相等。
- 对于每种数字 c,c 在 a 中出现的次数等于 c 在 b 中出现的次数。
此时,我们就称 a 和 b 近似匹配,即 a≈b。例如,(1,3,1,1,2)≈(2,1,3,1,1)。
UCloud 每年会收集若干不安全秘钥,这些秘钥组成了不安全秘钥集合 T。对于一个秘钥 s 和集合 T 中的秘钥 t 来说,它们的相似值定义为:s 的所有连续子串中与 t 近似匹配的个数。相似值越高,说明秘钥 s 越不安全。对于不安全秘钥集合 T 中的每个秘钥 t,你需要输出它和秘钥 s 的相似值,用来对用户秘钥的安全性进行分析。
输入格式
第一行包含一个正整数 n,表示 s 串的长度。
第二行包含 n 个正整数 s1,s2,...,sn(1≤si≤n),表示 s 串。
接下来一行包含一个正整数 m,表示询问的个数。
接下来 m 个部分:
每个部分第一行包含一个正整数 k(1≤k≤n),表示每个 t 串的长度。
每个部分第二行包含 k 个正整数 t1,t2,...,tk(1≤ti≤n),表示 T 中的一个串 t。
输入数据保证 T 中所有串长度之和不超过 200000。
对于简单版本:1≤n,m≤100;
对于中等版本:1≤n≤50000,1≤m≤500;
对于困难版本:1≤n≤50000,1≤m≤100000。
输出格式
输出 m 行,每行一个整数,即与 T 中每个串 t 近似匹配的 s 的子串数量。
样例解释
对于第一个询问,(3,2,1,3)≈(2,3,1,3),(3,2,1,3)≈(3,1,3,2);
对于第二个询问,(1,3)≈(3,1),(1,3)≈(1,3);
对于第三个询问,(3,2)≈(2,3),(3,2)≈(3,2)。
样例输入
5 2 3 1 3 2 3 4 3 2 1 3 2 1 3 2 3 2
样例输出
2 2 2
题目核心:两个集合相等;
思路:给每个数一个随机的64位无符号整数,作为哈希值;由于T中所有串长度之和不超过200000,对于一次m的询问k(即s串长)的种数最多同时存在x(x+1)/2=200000,约等于650种;那么可以离线将同等长度的存在一起,然后求s串的各种长度哈希值,排序二分搜索即可得到答案;
时间复杂度:O(sqrt(T.lenth())*n*logn)
代码:
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <vector>
#include <utility>
const int maxn=5e4+10;
using namespace std;
typedef unsigned long long ull;
int n,m,k,temp;
vector<pair<int,ull> >vec[maxn];
vector<int> v;
ull has[maxn],Shash[maxn];
int ans[maxn],flag[maxn],s[maxn];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
has[i]=(ull)rand()*rand();
for(int i=1; i<=n; i++){
scanf("%d",&s[i]);
}
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
ull t=0;
scanf("%d",&k);
if(!flag[k]) v.push_back(k),flag[k]=1;//标志多少长度种类;
for(int j=0;j<k;j++){
scanf("%d",&temp);
t+=has[temp];
}
vec[k].push_back(make_pair(i,t));
}
for(int i=0;i<v.size();i++)
{
int now=v[i];
int count=0;
Shash[0]=0;
for(int j=1;j<=now;j++)
Shash[count]+=has[s[j]];
for(int j=now+1;j<=n;j++)
{
count++;
Shash[count]=Shash[count-1]+has[s[j]]-has[s[j-now]];
}
sort(Shash,Shash+count+1);
for(int j=0;j<vec[now].size();j++)
{
ans[vec[now][j].first]=upper_bound(Shash,Shash+count+1,vec[now][j].second)-lower_bound(Shash,Shash+count+1,vec[now][j].second);
}
}
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
return 0;
}
通过率50%,程序暂定...