Gym

来源:互联网 发布:淘宝虚假交易处罚2016 编辑:程序博客网 时间:2024/05/22 06:32

Gym 101350A Sherlock Bones

The great dog detective Sherlock Bones is on the verge of a new discovery. But for this problem, he needs the help of his most trusted advisor you to help him fetch the answer to this case.

He is given a string of zeros and ones and length N.

Let F(x,y) equal to the number of ones in the string between indices x and y inclusively.

Your task is to help Sherlock Bones find the number of ways to choose indices(i,j,k) such that i<j<k, sj is equal to 1, and F(i,j)is equal to F(j,k).

Input

The first line of input is T – the number of test cases.
The first line of each test case is an integerN(3N2×105).
The second line is a string of zeros and ones of length N.

Output

For each test case, output a line containing a single integer- the number of ways to choose indices (i,j,k).

Example Input

3
5
01010
6
101001
7
1101011

Output

2
3
7

原题链接

题意:
给你一个01串str,f(i,j)定义为区间[i,j]内1的个数,求区间 [i,j,k]f(i,j) =f(j,k) 的情况的字串总数,要求str[j]=='1';
思路:
当确定ik的位置,那么对应的j的位置是唯一的。只要求区间[i,k]1出现奇数次,那么就有一个j满足要求。
求出01串的前缀xor和,Pre[i] 记录 [0,i] 区间内1出现的奇偶次数。然后倒着枚举i,根据Pre数组的值可以确定可以匹配的k的值,确定一组i,k也就是确定了i,j,k

#include <algorithm>#include <iostream>#include <fstream>#include <cstring>#include <cstdlib>#include <vector>#include <cstdio>#include <bitset>#include <string>#include <cmath>#include <ctime>#include <queue>#include <stack>#include <list>#include <map>#include <set>using namespace std;//#define LOCALconst int maxn=1e6+100;int Pre[maxn];int g[maxn][2];int main(){    ios::sync_with_stdio(false);    int T;    cin>>T;    while(T--){        memset(Pre,0,sizeof(Pre));        memset(g,0,sizeof(g));        int n;        cin>>n;        string s;        cin>>s;        for(int i=0;i<n;i++){            Pre[i+1]=Pre[i]^(s[i]-'0');        }        for(int i=n;i>=0;i--){            if(Pre[i]==0){                g[i][0]=g[i+1][0]+1;                g[i][1]=g[i+1][1];            }else{                g[i][0]=g[i+1][0];                g[i][1]=g[i+1][1]+1;            }        }        int last=n+1;        int flag=0;        long long ans=0;        s="0"+s;        for(int i=n;i>0;i--){            if(!flag){                if(s[i]=='1'){                    last=i;                    flag=1;                }            }else{                if(Pre[i-1]==0){                    ans+=g[last+1][1];                }else{                    ans+=g[last+1][0];                }                if(s[i]=='1'){                    last=i;                }            }        }        cout<<ans<<endl;    }    return 0;}
原创粉丝点击