CodeForces 1005D Polycarp and Div 3(思维、贪心、dp)

http://codeforces.com/problemset/problem/1005/D

 

 题意:

给一个仅包含数字的字符串,将字符串分割成多个片段(无前导0),求这些片段里最多有多少是3的倍数

思路一(贪心):

from:https://blog.csdn.net/islittlehappy/article/details/81006849

一个数是3的倍数,则各位的和能被3整除。

对于单独的一个数字,如果是3的倍数,则ans++

否则,考虑连续的两个数字,如果是,则ans++

如果第三个数本身是3的倍数,则ans++

如果第三个数不是3的倍数,则对于前两个数的和对3取余,结果为[1,1]或者[2,2](如果为[1,2],[2,1],则这两个数字能够被3整除)

对于第三个数对3取余,结果为0,1,2

0:第三个数本身能被3整除ans++

1:[1,1,1]是3的倍数取全部,[2,2,1]取后两个   ans++

2:[1,1,2]取后两个 [2,2,2]是3的倍数,取全部  ans++

所以 对于n=3 一定可以找到

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 const int maxn = 2e5+5;
 5 
 6 char str[maxn];
 7 
 8 int main()
 9 {
10     scanf("%s",str);
11     int t=0,sum=0,ans=0,n=0;
12     for(int i=0;i<strlen(str);i++)
13     {
14         t=(str[i]-'0')%3;
15         sum+=t;
16         n++;
17         if(t==0||sum%3==0||n==3)
18         {
19             ans++;
20             n=sum=0;
21         }
22     }
23     printf("%d\n",ans);
24     return 0;
25 }

思路二(dp):

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <iostream>
 4 #include <string>
 5 #include <math.h>
 6 #include <algorithm>
 7 #include <vector>
 8 #include <stack>
 9 #include <queue>
10 #include <set>
11 #include <map>
12 #include <sstream>
13 const int INF=0x3f3f3f3f;
14 typedef long long LL;
15 const int mod=1e9+7;
16 //const double PI=acos(-1);
17 #define Bug cout<<"---------------------"<<endl
18 const int maxm=1e6+10;
19 const int maxn=1e6+10;
20 using namespace std;
21 
22 char str[maxn];
23 LL sum[maxn];//前缀和 
24 int dp[maxn];//dp[i]表示前i个数的答案 
25 
26 int main()
27 {
28     scanf("%s",str+1);
29     for(int i=1;str[i];i++)
30     {
31         if(i==1)
32             sum[i]=str[i]-'0';
33         else
34             sum[i]=sum[i-1]+str[i]-'0';
35     }
36     int num=0;
37     if((str[1]-'0')%3==0)
38         dp[1]=1;
39     for(int i=2;str[i];i++)
40     {
41         if((str[i]-'0')%3==0)
42             dp[i]=dp[i-1]+1;
43         else
44         {
45             for(int j=i-1;j>0;j--)
46             {
47                 if((sum[i]-sum[j-1])%3==0)
48                 {
49                     dp[i]=max(dp[i],dp[j-1]+1);
50                     break;
51                 }
52                 else
53                     dp[i]=dp[i-1];
54             }
55         }
56     }
57     printf("%d\n",dp[strlen(str+1)]);
58     return 0;
59 }

猜你喜欢

转载自www.cnblogs.com/jiamian/p/11804471.html