Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.
Sereja needs to rush to the gym, so he asked to find all the described positions of q.
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
5 3 1 1 2 3 2 1 1 2 3
2 1 3
6 3 2 1 3 2 2 3 1 1 2 3
2 1 2
题目大意:
给你一个长度为N的数组a。
还给你了一个长度为M的数组b。
问你有多少个位子p,使得:ap,ap+q,ap+2q..................的序列是和b数组一样的序列(位子无所谓,只要元素个数一一对应即可。)
思路:
1、我们不难想到,暴力枚举一个起点,然后暴力判断其之后的长度为m的ap,ap+q,ap+2q................序列是否满足条件,如果满足,那么cnt++.
显然这种做法是O(n^2)的,我们一定会超时。
那么考虑进行优化:
如果我们对应起点当前是1,假设m=4,q=2,那么对应此时区间内有:
a1,a3,a5,a7
如果我们对应起点是5,同时m=4,q=2,那么对应此时区间内有:
a5,a7,a9,a11
不难发现,起点不同的两个序列,其中有很大一部分的重叠,那么我们我们考虑优化掉这些冗杂的操作。
2、对应我们直接枚举起点分别为1,2,3,4.........p,接下来进行暴力处理,对应假设我们起点为1,m=4,q=2;
那么我们暴力判断a1,a3,a5,a7,之后,去掉a1,加入a9.此时判断的就是a3,a5,a7,a9这一段序列,那么同理,再去掉a3,加入a11,此时判断的就是a5,a7,a9,a11这一段序列。
判断的过程我们用map进行计数即可。
那么依次类推,将从1到p作为起点的全部子序列都进行如上过程的判断,其时间复杂度约为:O(n)
Ac代码:
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
int a[200600];
int b[200600];
int ans[200600];
map<int ,int >bb;
int n,m,p,cnt,cont;
void Slove(int ss)
{
map<int ,int >s;
int sum=0;
int pre=ss;
for(int i=ss;i<=n;i+=p)
{
if(s[a[i]]==bb[a[i]])sum--;
s[a[i]]++;
if(s[a[i]]==bb[a[i]])sum++;
if((i-pre)/p>=m-1)
{
if((i-pre)/p==m-1)
{
if(sum==cnt)ans[cont++]=ss;
}
else
{
if(s[a[i-m*p]]==bb[a[i-m*p]])sum--;
s[a[i-m*p]]--;
if(s[a[i-m*p]]==bb[a[i-m*p]])sum++;
if(sum==cnt)ans[cont++]=i-(m-1)*p;
}
}
}
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&p))
{
cnt=0;
cont=0;
bb.clear();
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(int i=1;i<=m;i++)
{
scanf("%d",&b[i]);
bb[b[i]]++;
if(bb[b[i]]==1)cnt++;
}
for(int i=1;i<=p;i++)
{
if(i+(m-1)*p<=n)
{
Slove(i);
}
else break;
}
printf("%d\n",cont);
sort(ans,ans+cont);
for(int i=0;i<cont;i++)
{
printf("%d ",ans[i]);
}
printf("\n");
}
}