C. Unstable String

https://codeforces.com/contest/1535/problem/C

原题:
You are given a string s
consisting of the characters 0, 1, and ?.
Let’s call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101… or 101010…).
Let’s call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.
For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.
Calculate the number of beautiful contiguous substrings of the string s
.
Input
The first line contains a single integer t(1≤t≤10^4) — number of test cases.
The first and only line of each test case contains the string s(1≤|s|≤2⋅10^5) consisting of characters 0, 1, and ?.
It is guaranteed that the sum of the string lengths over all test cases does not exceed 2⋅10^5
.
Output
For each test case, output a single integer — the number of beautiful substrings of the string s
.
Example
Input

3
0?10
???
?10??1100

Output

8
6
25

题意:
给出几串字符串,都是由 ?,1,0 组成的,其中的 ? 可以变成 1 或者 0 ,问这其中连续的子序列且相邻元素均不相同的有几个

思路(我的可能不是那木简洁):
用一个x来记录不相同的个数,从头开始判断遇到不相同的或者两个 ?,x就加一,通过下面的例子可以看出来,x是几,这一个子串就包含了几个小子串,然后随时更改 ?的值。
当遇到两个相同的时候,x就要重新开始记录,特别的是,当这个重复的元素前面有 ?的时候,x并不是从一开始的,而是加上前面连续的 ?个数,因为 ?可以改变为任意值。

例1的情况:

0
0?        ?
?1        1
?10       10       0

例3:

?
?1          1
?10         10         0
?10?        10?        0?        ?
?10??       10??       0??       ??       ?
?10??1      10??1      0??1      ??1      ?1      1
1 
10          0
0

代码:


#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <cstdio>
#include <string>
using namespace std;

typedef long long  ll;
string s,a;
int main()
{
    int t,n,j;
    cin>>t;
    while(t--)
    {
        cin>>s;
        a=s;//用一个新的字符串保留原来的值,因为要随时改变 ?的值
        ll x=1,y,sum=1,q=0;
        int l=s.length();
        for(int i=0;i<l-1;i++)
        {
            if(s[i]!=s[i+1]||(s[i]= =' ? '&&s[i+1]= =' ? '))//两个相邻的不相同或者是两个?
            {
                if(s[i]!=' ? '&&s[i+1]= =' ? ')//改变?的值
                {
                    if(s[i]= =' 1 ')   s[i+1]=' 0 ';
                    else s[i+1]=' 1 ';
                }
                x++;
                sum+=x;
            }
            else if(s[i]= =s[i+1])//两个相同
            {
                x=1;
                j=i;
                y=1;
                for(;j>=0;j--)
                {
                    if(a[j]= ='?') y++;
                    else break;
                }
                if(a[i]= =' ? ')  x=y;//当此时是 ? 的时侯,x的值是加上问号的总长度
                sum+=y;
            }
        }
        cout<<sum<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值