number
题目描述
300iq loves numbers who are multiple of 300.
One day he got a string consisted of numbers. He wants to know how many substrings in the string are multiples of 300 when considered as decimal integers.
Note that leading and trailing zeros are allowed (both in original string and substrings you chose) and the same substring appearing in different places can be counted multiple times.
输入描述:
A single line consisting a string consisted of characters '0' to '9'.
输出描述:
The number of substrings that are multiples of 300 when considered as decimal integers.
示例1
备注:
let the string in the input be s, 1 \leq |s| \leq 10^51≤∣s∣≤105.
给一个字符串,问有多少个子串能够整除 300 , 包含前导 0 。
dp[i][j] 表示在 i 位置及之前所有位置形成的数 % 300 == j 的数量
那么当前状态可推向 [i + 1][(j * 10 + s[i + 1] - '0') % 300]
故有状态转移方程 dp[i][(j * 10 + s[i] - '0') % 300] += dp[i - 1][j] .. 每一次注意初始值 dp[i][s[i] - '0'] = 1.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include<bits/stdc++.h> #define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl #define pii pair<int,int> #define clr(a,b) memset((a),b,sizeof(a)) #define rep(i,a,b) for(int i = a;i < b;i ++) #define pb push_back #define MP make_pair #define LL long long #define ull unsigned LL #define ls i << 1 #define rs (i << 1) + 1 #define INT(t) int t; scanf("%d",&t) using namespace std; const int maxn = 1e5 + 10; LL dp[maxn][310]; char s[maxn]; int main() { while(~scanf("%s",s + 1)){ int len = strlen(s + 1); clr(dp,0); for(int i = 1;i <= len;++ i){ int tmp = s[i] - '0'; dp[i][tmp] = 1; for(int j = 0;j < 300;++ j) dp[i][(j * 10 + tmp) % 300] += dp[i - 1][j]; } LL ans = 0; for(int i = 1;i <= len;++ i) ans += dp[i][0]; cout << ans << endl; } return 0; }
当然这个题也可以前缀和做,显然 % 300 == 0 需要两个条件,末尾两个0,前面的 % 3 == 0,故可以记录当前位置之前 前缀和 % 3 == 0, 1 , 2 的数量,然后加上对应的数量即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include<bits/stdc++.h> #define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl #define pii pair<int,int> #define clr(a,b) memset((a),b,sizeof(a)) #define rep(i,a,b) for(int i = a;i < b;i ++) #define pb push_back #define MP make_pair #define LL long long #define ull unsigned LL #define ls i << 1 #define rs (i << 1) + 1 #define INT(t) int t; scanf("%d",&t) using namespace std; const int maxn = 1e5 + 10; char s[maxn]; int sum[maxn]; int mp[maxn * 10]; int main() { while(~scanf("%s",s + 1)){ clr(mp,0); int sz = strlen(s + 1); LL ans = 0; for(int i = 1;i <= sz;++ i){ sum[i] = sum[i - 1] + s[i] - '0'; sum[i] %= 3; if(s[i] == '0') ++ ans; } for(int i = 1;i + 1 <= sz;++ i){ if(s[i] == '0' && s[i + 1] == '0'){ ++ ans; // printf("===>%d , ",mp[sum[i - 1]]); debug(sum[i - 1]); ans += mp[sum[i - 1]]; if(sum[i - 1] % 3 != 0) -- ans; } // debug(ans); ++ mp[sum[i]]; } // debug(ans); cout << ans << endl; } return 0; }