HackerRank Super Six Substrings dp
生活随笔
收集整理的這篇文章主要介紹了
HackerRank Super Six Substrings dp
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://www.hackerrank.com/contests/hourrank-18/challenges/super-six-substrings
能被6整除的數有一個特點,就是能同時被3和被2整除
那么也就是能整除3的偶數。
設dp[i][j]表示以第i位結尾的所有子串中,%3的余數是j的方案數,
dp[i + 1][(j * 10 + nowNumber) % 3] = dp[i][j]
注意那個 * 10是必須的,因為從第i項轉移過來,位數應該移動一位。就比如,12
1 % 3 = 1, 然后加入一個2,是1 * 10 + 2 = 12 % 3 = 0
但是這里又不是必須的,因為10 % 3 = 1,所以相當于沒加。
現在說說那個0, 0是不能做前綴的,怎么破、
對于0,只算一個貢獻,不加進去dp統計那里就行。
#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?
轉載于:https://www.cnblogs.com/liuweimingcprogram/p/6546661.html
總結
以上是生活随笔為你收集整理的HackerRank Super Six Substrings dp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RTC-IC-PCF2129
- 下一篇: Netty内存池