description
定义两个由数字序列组成的秘钥 a 和
- |a|=|b|,即 a 串和
b 串长度相等。 - 对于每种数字 c,
c 在 a 中出现的次数等于c 在 b 中出现的次数。
对于秘钥
它们的相似值定义为:s 的所有连续子串中与
Solution
题目的近似匹配其实就是两个多重集合相等。
把每个元素赋上一个64位整数的Hash值。一个多重集合的Hash值为所有元素Hash值的和。
因为
∑leni≤200000
所以将所有询问按长度分类后种类只会有O(∑leni−−−−−−√)种,每次O(n)在map中查询哈希值。时间复杂度O(n∑leni−−−−−−√)。
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int P = 1010107;
const int N = 202020;
typedef unsigned long long ull;
typedef pair<ull, int> Pair;
inline char get(void) {
static char buf[100000], *S = buf, *T = buf;
if (S == T) {
T = (S = buf) + fread(buf, 1, 100000, stdin);
if (S == T) return EOF;
}
return *S++;
}
template<typename T>
inline void read(T &x) {
static char c; x = 0;
for (c = get(); c < '0' || c > '9'; c = get());
for (; c >= '0' && c <= '9'; c = get()) x = x * 10 + c - '0';
}
struct Map {
int head[P], vis[P];
struct edge {
ull ori;
int key, next;
edge(ull o = 0, int k = 0, int n = 0): ori(o), key(k), next(n) {}
};
edge G[N * 10];
int Gcnt, clc;
Map(void) {
clc = 1;
for (int i = 0; i < P; i++) vis[i] = 0;
}
inline void Clear(void) {
Gcnt = 0; clc++;
}
inline int Head(int x) {
if (vis[x] == clc) return head[x];
else {
vis[x] = clc; return head[x] = 0;
}
}
inline void AddEdge(int from, ull ori, int key) {
G[++Gcnt] = edge(ori, key, head[from]); head[from] = Gcnt;
}
inline int &operator [](ull x) {
int h = x % P;
for (int i = Head(h); i; i = G[i].next)
if (G[i].ori == x) return G[i].key;
AddEdge(h, x, 0); return G[Gcnt].key;
}
};
Map M;
ull h[N], H[N];
int s[N], ans[N];
int n, q, m, t;
vector<Pair> Q[N];
inline ull Rand(void) {
return (ull)rand() << 30 | rand();
}
int main(void) {
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
srand(19260817);
read(n);
for (int i = 1; i <= n; i++) {
read(s[i]); h[i] = Rand();
}
for (int i = 1; i <= n; i++)
H[i] = H[i - 1] + h[s[i]];
read(q);
for (int i = 1; i <= q; i++) {
read(m); ull val = 0;
for (int j = 1; j <= m; j++) {
read(t); val = val + h[t];
}
Q[m].push_back(Pair(val, i));
}
for (int k = 1; k <= n; k++)
if (Q[k].size()) {
M.Clear();
for (int i = 1; i + k - 1 <= n; i++)
M[H[i + k - 1] - H[i - 1]]++;
for (int i = 0; i < Q[k].size(); i++)
ans[Q[k][i].second] = M[Q[k][i].first];
}
for (int i = 1; i <= q; i++)
printf("%d\n", ans[i]);
return 0;
}