Topic Links: Codeforces Round #112 (Div. 2) C Another problem on Strings
Test instructions: A sequence containing only 0,1 is given, and the number of sub-sequences in the sequence and n is obtained.
Idea: Preprocessing the prefix of a sequence and then enumerating the sequence, recording (VIS) the number of prefixes that existed before the position, and then querying (SUM[I]-N), that is, the number of sub-sequences ending with that position and N.
Note: 0 in the VIS array should always exist, initialize vis[0]=1 (why, because sum[i] itself equals N to calculate a method number).
Extrapolate: Similar can be obtained, the number of substrings in any sequence and n is an O (n algorithm).
If there is something wrong, please correct me!
AC Code:
#include <stdio.h> #include <string> #include <string.h> #include <iostream> #define LL __ int64using namespace Std;string str; LL sum[1000010]; ll Vis[1000010];int Main () {LL n,len,i;while (cin>>n) {cin>>str;memset (vis,0,sizeof vis); Len=str.length () ; Vis[0]=1;for (i=0;i<len;i++) {if (i==0) sum[i]=str[i]-' 0 '; else sum[i]=sum[i-1]+str[i]-' 0 ';} ll Ans=0;for (i=0;i<len;i++) {if (sum[i]>=n) {LL u=sum[i]-n;ans+=vis[u];} vis[sum[i]]++;} printf ("%i64d\n", ans);} return 0;}
Codeforces Round #112 (Div. 2) C Another problem on Strings