Codeforces 1295B Infinite Prefixes

传送门

题意:

给两个整数n,x;
然后一行长度为n的01字符串s
t字符串为s的无限循环构成 t = s s s s s s t=ssssss t=ssssss
c n t 0 , q − c n t 1 , q cnt_0,q−cnt _1,q cnt0,qcnt1,q等于q字符串中0的个数减去1的个数
问有多少可能的t的前缀子串的 c n t 0 , q − c n t 1 , q cnt_0,q−cnt _1,q cnt0,qcnt1,q==x
如果有无限个输出-1

思路:

1 , 1, 1有无限个的情况就是,能找到 c n t 0 , q − c n t 1 , q cnt_0,q−cnt _1,q cnt0,qcnt1,q==x,并且s字符串中0,1的个数相等
2 , 2, 2答案为0的情况,在s串中不能找到 c n t 0 , q − c n t 1 , q cnt_0,q−cnt _1,q cnt0,qcnt1,q==x,并且s字符串中0,1的个数相等
3 , 3, 3正常情况下,把s串处理一下,每个位置求出0的个数减去1的个数的值,记录0的个数减去1的个数的值出现的次数,求出p为一整个字串0的个数减去1的个数的值,如果该值能通过好几个s串变成x(即 c n t 0 , q − c n t 1 , q cnt_0,q−cnt _1,q cnt0,qcnt1,q+k*p = = == ==x,显然k>=0,k是往后面再循环几个s串),那么就加上该值的个数,详见代码

代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxn=1e5+50;
char ch[maxn];
int a[maxn];
int main()
{
    int t,n,x;
    scanf("%d",&t);
    while(t--){
       scanf("%d%d ",&n,&x);
       map<int,int>h;
       int s1=0,s0=0;
       int ans=0;
       int ma=-maxn,mi=maxn;
       for(int i=1;i<=n;i++){
       scanf("%c",&ch[i]);
       if(ch[i]=='1')s1++;
       if(ch[i]=='0')s0++;
       if(s0-s1==x)ans++;
       h[s0-s1]++;//记录s0-s1值的个数
       ma=max(ma,s0-s1);
       mi=min(mi,s0-s1);
       }
       int p=s0-s1;
       if(ans>0&&p==0){//无限个的情况
           printf("-1\n");
           continue;
       }
       if(p==0&&ans==0){//为0的情况
           printf("0\n");
           continue;
       }
       ans=0;
       for(int i=mi;i<=ma;i++){//之前用的i=-maxn;i<=maxn,竟然t61组数据了,不应该啊,换成mi,ma就过了,tmd;
           if(p>0&&(x-i)%p==0&&(x-i)>=0)ans+=h[i];//负数不能取模,分开讨论,而且x-i必须与p同号
           if(p<0&&(x-i)<=0&&(i-x)%(-p)==0)ans+=h[i];
       }
       if(x==0)//特判
           ans++;//因为前缀为空串的时候也算,所以,x==0时,+1
        printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值