2019 cattle off more training school fourth K.number (thinking)

Topic Portal

Meaning of the questions:

Enter a numeric string containing only obtained is a multiple of the number of substrings 300 (0,00,000 different positions so calculated, and consider the case of leading zeros).

sample input:

600

123000321013200987000789

sample output:

4

55

answer:

O (n) approach: iterate again, seeking to take the prefix and the sum of more than 3, the number of statistical sum of the num [sum], experience-based and next are 0, the statistics put the number before adding, finally add the number 0 alone.

O (300n) DP practices: the following

Official Solution:

Code:

O (n), the following:

 /*6ms*/
1
#include<bits/stdc++.h> 2 typedef long long ll; 3 using namespace std; 4 const int M=1e5+5; 5 char s[M]; 6 int main() 7 { 8 while(~scanf("%s",s+1)) 9 { 10 int len=strlen(s+1),sum=0,num[3]={}; 11 ll cnt=0; 12 num[0]=1; 13 for(int i=1;i<=len;i++){ 14 sum=(sum+(s[i]-'0'))%3; 15 if(s[i]=='0'&&s[i+1]=='0'){ 16 cnt+=num[sum]; 17 } 18 if(s[i]=='0')cnt++; 19 num[sum]++; 20 } 21 printf("%lld\n",cnt); 22 } 23 return 0; 24 }

 DP approach is as follows [O (300n)]:

 /*224ms*/
1
#include<bits/stdc++.h> 2 typedef long long ll; 3 using namespace std; 4 const int M=1e5+5; 5 char s[M]; 6 int dp[M][302]; 7 int main() 8 { 9 while(~scanf("%s",s+1)) 10 { 11 memset(dp,0,sizeof(dp)); 12 dp[1][s[1]-'0']=1; 13 int len=strlen(s+1); 14 for(int i=2;i<=len;i++){ 15 dp[i][s[i]-'0']++; 16 for(int j=0;j<300;j++){ 17 int flag=(j*10+s[i]-'0')%300; 18 dp[i][flag]+=dp[i-1][j]; 19 } 20 } 21 ll ans=0; 22 for(int i=1;i<=len;i++) 23 ans+=dp[i][0]; 24 printf("%lld\n",ans); 25 } 26 return 0; 27 }

 

Guess you like

Origin www.cnblogs.com/HOLLAY/p/11264713.html