Codeforces 1295B Infinite Prefixes

传送门

题意:

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

思路:

\(1,\)有无限个的情况就是,能找到\(cnt_0,q−cnt _1,q\)x,并且s字符串中0,1的个数相等
\(2,\)答案为0的情况,在s串中不能找到\(cnt_0,q−cnt _1,q\)
x,并且s字符串中0,1的个数相等
\(3,\)正常情况下,把s串处理一下,每个位置求出0的个数减去1的个数的值,记录0的个数减去1的个数的值出现的次数,求出p为一整个字串0的个数减去1的个数的值,如果该值能通过好几个s串变成x(即\(cnt_0,q−cnt _1,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;
}
posted @ 2020-02-01 23:05  _Alexander  阅读(165)  评论(0编辑  收藏  举报