CF1930D2.Sum over all Substrings (Hard Version)

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

This is the hard version of the problem. The only difference between the two versions is the constraint on tt and nn . You can make hacks only if both versions of the problem are solved.

For a binary ^\dagger pattern pp and a binary string qq , both of length mm , qq is called pp -good if for every ii ( 1im1 \leq i \leq m ), there exist indices ll and rr such that:

  • 1lirm1 \leq l \leq i \leq r \leq m , and
  • pip_i is a mode ^\ddagger of the string qlql+1qrq_l q_{l+1} \ldots q_{r} .

For a pattern pp , let f(p)f(p) be the minimum possible number of 1\mathtt{1} s in a pp -good binary string (of the same length as the pattern).

You are given a binary string ss of size nn . Find $$$$\sum_{i=1}^{n} \sum_{j=i}^{n} f(s_i s_{i+1} \ldots s_j). $$ In other words, you need to sum the values of ff over all fracn(n+1)2\\frac{n(n+1)}{2} substrings of ss .

^\\dagger A binary pattern is a string that only consists of characters mathtt0\\mathtt{0} and mathtt1\\mathtt{1} .

^\\ddagger Character cc is a mode of string tt of length mm if the number of occurrences of cc in tt is at least lceilfracm2rceil\\lceil \\frac{m}{2} \\rceil . For example, mathtt0\\mathtt{0} is a mode of mathtt010\\mathtt{010} , mathtt1\\mathtt{1} is not a mode of mathtt010\\mathtt{010} , and both mathtt0\\mathtt{0} and mathtt1\\mathtt{1} are modes of mathtt011010\\mathtt{011010}$$.

输入格式

Each test contains multiple test cases. The first line contains the number of test cases tt ( 1t1051 \le t \le 10^5 ) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer nn ( 1n1061 \le n \le 10^6 ) — the length of the binary string ss .

The second line of each test case contains a binary string ss of length nn consisting of only characters 0\mathtt{0} and 1\mathtt{1} .

It is guaranteed that the sum of nn over all test cases does not exceed 10610^6 .

输出格式

For each test case, output the sum of values of ff over all substrings of ss .

输入输出样例

  • 输入#1

    4
    1
    1
    2
    10
    5
    00000
    20
    11110110000000111111

    输出#1

    1
    2
    0
    346

说明/提示

In the first test case, the only 1\mathtt{1} -good string is 1\mathtt{1} . Thus, f(1)=1f(\mathtt{1})=1 .

In the second test case, f(10)=1f(\mathtt{10})=1 because 01\mathtt{01} is 10\mathtt{10} -good, and 00\mathtt{00} is not 10\mathtt{10} -good. Thus, the answer is f(1)+f(10)+f(0)=1+1+0=2f(\mathtt{1})+f(\mathtt{10})+f(\mathtt{0}) = 1 + 1 + 0 = 2 .

In the third test case, ff equals to 00 for all 1ij51 \leq i \leq j \leq 5 . Thus, the answer is 00 .

首页