Codeforces Round #215_div2_D. Sereja ans Anagrams

转载注明出处  http://blog.csdn.net/moedane

 

 

 

传送门 http://codeforces.com/contest/368/problem/D

 

 

题意

给出a,b数组,以及整数p,求所有的q,使得a[q],a[q+p],a[q+2p]...a[q+(m-1)p]等于任意重新排列后的b数组。即b数组中的每一个数都能与上述选出来的数列对应。

 

思路

枚举q1p,把a数组中以q为开头的间隔p的所有数取出来作为一个新数列。

初始化时用map<int,int>,把b数组中的数存入map中,然后再在新数列里扫过去,每扫到一个数,就map[a[j]] --,如果长度超过了m,则把a[j - m*p]那个数放回map里(保证map里存的数的数量是m个),这样做的意思是,这时的起点已经由j - m*p 改变到(j - m*p + p)。

每扫一个数还要做的操作是,如果map中某个key的值为0,则erase这个key。这样判断当前起点是否合法就便利了,只要判断当前map是否为空即可(为空则代表选取的这一段恰好能跟b数组一一对应)。

 

T_T这个题T了好久,原因是每一次都做了初始化。后来做一些处理把初始化放到外面,只做一次,就A了。

复杂度似乎是O(nlogn)的,虽然常数大了点……

 

代码

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <cctype>
#define bug puts("here");

using namespace std;

typedef long long ll;

const int maxn = 2 * 100086;
const int mod = 1000000007;
const double PI = atan(1.0)*4.0;

map<int,int> mp;
int a[maxn],b[maxn];
int n,m,p;
vector<int> ans;

void init()
{
    mp.clear();
    int i;
    for(i=1;i<=m;i++)
        mp[b[i]] ++;
    return;
}

int main()
{
    ans.clear();
    scanf("%d%d%d",&n,&m,&p);
    int i,j;
    for(i=1;i<=n;i++)
        scanf("%d",a+i);
    for(i=1;i<=m;i++)
        scanf("%d",b+i);
    init();
    for(i=1;i<=p;i++)
    {
        if(i + (m-1) * p > n) break;
        int e = 1;
        for(j=i;j<=n;j+=p,e++)
        {
            int tmp = j - m * p;
            if(e <= m)
            {
                mp[a[j]] --;
                if(mp[a[j]] == 0) mp.erase(a[j]);
            }
            else
            {
                mp[a[tmp]] ++;
                mp[a[j]] --;
                if(mp[a[j]] == 0) mp.erase(a[j]);
                if(mp[a[tmp]] == 0) mp.erase(a[tmp]);
            }
            if(e>=m && mp.size() == 0) ans.push_back(j - (m-1) * p);
            if(j+p > n)
            {
                for(int k = tmp+p;k<=n;k+=p)
                {
                    mp[a[k]] ++;
                    if(mp[a[k]] == 0) mp.erase(a[k]);
                }
            }
        }
    }
    sort(ans.begin(),ans.end());
    int cnt = ans.size();
    printf("%d\n",cnt);
    for(i=0;i<cnt - 1;i++)
        printf("%d ",ans[i]);
    if(cnt > 0) printf("%d\n",ans[i]);
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值