日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【牛客 - 1080E】tokitsukaze and Segmentation(dp,递推,思维)

發布時間:2023/12/10 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【牛客 - 1080E】tokitsukaze and Segmentation(dp,递推,思维) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題干:

鏈接:https://ac.nowcoder.com/acm/contest/1080/E
來源:牛客網
?

tokitsukaze有一個長度為n的字符串,字符串僅包含'0'-'9'。
tokitsukaze要把這個字符串切割成若干個子串,每個子串作為一個十進制的數,能被3整除,且不含前導0。
問有多少種切割的方案。由于答案可能很大,請輸出mod 998244353 后的結果。

輸入描述:

第一行包含一個正整數n,(1≤n≤10^5)。 第二行包含一個長度為n的字符串s,('0'≤s[i]≤'9')。

輸出描述:

輸出一個整數,表示方案數,mod 998244353 后的結果。

示例1

輸入

復制

1 1

輸出

復制

0

示例2

輸入

復制

1 0

輸出

復制

1

示例3

輸入

復制

4 1203

輸出

復制

3

說明

(1) 1203 (2) 120|3 (3) 12|0|3 所以方案數為3。 注意:12|03,視作不合法,因為有前導0。

解題報告:

? 看似一個dp題,其實直接遞推就可以了。其實如果數字中沒有0的話直接一個變量就可以了。但是這題有零所以需要開兩個變量。

先來一個TLE代碼:

#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; const ll mod = 998244353; char s[MAX]; ll dp[MAX]; int cur,tmp,n; int main() {cin>>n;cin>>(s+1);for(int i = 1; i<=n; i++) s[i] -= '0';dp[0] = 1;for(int i = 1; i<=n; i++) {cur = (cur+s[i])%3;tmp = cur;for(int j = i; j>=1; j--) {tmp = (tmp+9-s[j])%3;if(!tmp && cur == tmp && (s[j]!=0 || j==i)) dp[i] = (dp[i] + dp[j-1]) % mod;}}ll ans = 0;printf("%lld\n",dp[n]%mod);return 0 ; }

可以發現可以化簡成這樣:(來自題解)

for(int i=1;i<=n;i++) dp[i]=0; dp[0]=1; for(int i=1;i<=n;i++) {suf=0;for(int j=i;j;j--){suf=(suf+s[j]-'0')%3;if(s[j]=='0'&&j<i) continue;if(!suf) (dp[i]+=dp[j-1])%=mod;} }

也就是說特點就是要找前綴數字和是0的方案數,然后累加一下就行了。但是因為有前導0,所以要開兩個變量分別記錄。

AC代碼:

#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; const ll mod = 998244353; char s[MAX]; ll dp,sum; int cur,tmp,n; int main() {cin>>n;cin>>(s+1);sum = 1;for(int i = 1; i<=n; i++) s[i] -= '0';for(int i = 1; i<=n; i++) {cur = (cur+s[i])%3;if(cur == 0) {if(s[i] == 0) sum = (sum+dp)%mod;else sum = dp = (sum+dp)%mod;}}if(cur == 0) printf("%lld\n",sum);else printf("0\n");return 0 ; }

?

總結

以上是生活随笔為你收集整理的【牛客 - 1080E】tokitsukaze and Segmentation(dp,递推,思维)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。