C. Unstable String
题目大意:
t
t
t 组询问,每次给定一个仅包含字符
1
1
1 或
0
0
0 或
?
?
? 字符串
s
s
s。定义一个子串是不稳定的当且仅当子串中任意相邻两数均不相同,如 101010…101010… 或 010101…010101…。其中
?
?
? 可以变为
1
1
1 或
0
0
0 其中一种。请求出给定的
s
s
s 中最多可以有的不稳定子串个数。
思路:
这是在学校一天晚上跟lsc聚聚hz聚聚lyy聚聚一起打的一场,当时晚上研究了好久题意,想出来一种暴力的取法,但是没有实现出来。现在看来有了dp的想法。
如果当前位置为 0 0 0,那么使得该子串完美的情况即为 d p [ i ] [ 0 ] = d p [ i − 1 ] [ 1 ] + 1 dp[i][0]=dp[i - 1][ 1 ]+1 dp[i][0]=dp[i−1][1]+1,同理当前位置为 1 1 1,那么 d p [ i ] [ 1 ] = d p [ i − 1 ] [ 0 ] + 1 dp[i][1] = dp[i - 1][0] + 1 dp[i][1]=dp[i−1][0]+1,当该处为问号时,即进行两次操作选最大的的计数即可。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<iomanip>
#include<queue>
using namespace std;
typedef long long ll;
const int p = 1e9 + 7;
typedef pair<int, int> pii;
const int N = 2e5+10;
string s;
map<int,double>mp;
int ans[N][2];
int main() {
int n;
cin >> n;
while (n--)
{
memset(ans, 0, sizeof ans);
string s;
cin >> s;
s = " " + s;
ll h = 0;
for (int i = 1; i < s.length(); i++) {
if (s[i] == '0')ans[i][1] = ans[i - 1][0] + 1;
else if (s[i] == '1')ans[i][0] = ans[i - 1][1] + 1;
else {
ans[i][1] = ans[i - 1][0] + 1;
ans[i][0] = ans[i - 1][1] + 1;
}
h += max(ans[i][1], ans[i][0]);
}
cout << h << endl;
}
}