HackerRank Super Six Substrings dp
https://www.hackerrank.com/contests/hourrank-18/challenges/super-six-substrings
能被6整除的數(shù)有一個(gè)特點(diǎn),就是能同時(shí)被3和被2整除
那么也就是能整除3的偶數(shù)。
設(shè)dp[i][j]表示以第i位結(jié)尾的所有子串中,%3的余數(shù)是j的方案數(shù),
dp[i + 1][(j * 10 + nowNumber) % 3] = dp[i][j]
注意那個(gè) * 10是必須的,因?yàn)閺牡趇項(xiàng)轉(zhuǎn)移過(guò)來(lái),位數(shù)應(yīng)該移動(dòng)一位。就比如,12
1 % 3 = 1, 然后加入一個(gè)2,是1 * 10 + 2 = 12 % 3 = 0
但是這里又不是必須的,因?yàn)?0 % 3 = 1,所以相當(dāng)于沒(méi)加。
現(xiàn)在說(shuō)說(shuō)那個(gè)0, 0是不能做前綴的,怎么破、
對(duì)于0,只算一個(gè)貢獻(xiàn),不加進(jìn)去dp統(tǒng)計(jì)那里就行。
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <assert.h> #define IOS ios::sync_with_stdio(false) using namespace std; #define inf (0x3f3f3f3f) typedef long long int LL;#include <iostream> #include <sstream> #include <vector> #include <set> #include <map> #include <queue> #include <string> #include <bitset> const int maxn = 1e5 + 20; LL dp[2][3]; char str[maxn]; void work() {cin >> str + 1;int lenstr = strlen(str + 1);int now = 0;LL ans = 0;for (int i = 1; i <= lenstr; ++i) {now = !now;memset(dp[now], 0, sizeof dp[now]);int num = str[i] - '0';if (num == 0) {ans += dp[!now][0] + 1;memcpy(dp[now], dp[!now], sizeof dp[!now]);continue;}dp[now][num % 3] = 1;for (int j = 0; j <= 2; ++j) {dp[now][(j * 10 + num) % 3] += dp[!now][j];}if (num % 2 == 0) {ans += dp[now][0]; // if (str[i - 1] == '0') ans--; } // cout << ans << endl; }cout << ans << endl; }int main() { #ifdef localfreopen("data.txt", "r", stdin); // freopen("data.txt", "w", stdout); #endifwork();return 0; } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/liuweimingcprogram/p/6546661.html
總結(jié)
以上是生活随笔為你收集整理的HackerRank Super Six Substrings dp的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: RTC-IC-PCF2129
- 下一篇: Netty内存池