题解:P17806 [ICPC 2019 Nanchang R] And and Pair
somebody666 · · 题解
思路
条件
先考虑
因为
对于第
-
如果
n 当前位为1 ,则有三种选择:因此每个这样的位置有
3 种选择。 -
-
如果
n 当前位为0 ,则i 必须为0 ,而j 可以为0 或1 ,所以有2 种选择。
假设第
此外,
扫描计算
输入字符串是从高位到低位排列的,因此从右向左扫描,即从低位向高位处理。
设:
如果当前位为
如果当前位为
最后再加上
前导零也可以直接参与扫描,因为它们位于所有有效
证明
对于任意非零的
由于
构造出的
每个非零的
复杂度
设所有测试串的最大长度为
预处理幂数组的复杂度为
每组数据只需扫描一次字符串,时间复杂度为
参考代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define mod 1000000007
int t;
int p2[100005], p3[100005];
string s;
void init()
{
p2[0] = p3[0] = 1;
for(int i = 1;i <= 100000;i++)
{
p2[i] = p2[i-1] * 2 % mod;
p3[i] = p3[i-1] * 3 % mod;
}
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
init();
cin >> t;
while(t--)
{
cin >> s;
int cnt0 = 0, cnt1 = 0, ans = 0;
for(int i = s.size()-1;i >= 0;i--)
{
if(s[i] == '1')
{
ans = (ans + p3[cnt1] * p2[cnt0] % mod) % mod;
cnt1++;
}
else
{
cnt0++;
}
}
cout << (ans + 1) % mod << '\n';
}
return 0;
}
本题解在完成后用 ChatGPT 进行润色