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 indicesx andy inclusively.Your task is to help Sherlock Bones find the number of ways to choose indices
(i, j, k) such thati < j < k ,sj is equal to 1, andF(i, j) is equal toF(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(3 ≤ N ≤ 2 × 105).
The second line is a string of zeros and ones of lengthN .
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';
。
思路:
当确定i
和k
的位置,那么对应的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;}
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- Gym
- selinux
- 编程练习3——04
- 设计模式-中介者模式
- 编程练习3——05
- hdu1075-What Are You Talking About 字典树
- Gym
- Javascript--Array数组的splice()方法之删除、插入、替换
- 高德地图Marker与InfoWindow定位居中冲突问题
- CodeForces
- Laravel 引入没有命名空间的第三方类库
- HashMap和HashTable的简单比较
- C++之循环结构
- HDU_3791 二叉搜索树
- 《leetCode》:Remove Duplicates from Sorted Array