CF792C Divide by Three

思路:

dp。

实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <string>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int INF = 0x3f3f3f3f;
 9 
10 string s;
11 int n, cnt = 0;
12 int dp[100005][2][3]; 
13 int path[100005][2][3];
14 int ans[100005];
15 
16 int trans(int index)
17 {
18     return s[index] - '0';
19 }
20 
21 int dfs(int now, bool lz, int mod)
22 {
23     if (dp[now][lz][mod] != -1)
24         return dp[now][lz][mod];
25     if (now == n)
26     {
27         if (lz && !mod)
28             return 0;
29         return -INF;
30     }
31     int x, y = -INF;
32     x = dfs(now + 1, lz, mod);
33     path[now][lz][mod] = 0;
34     if (s[now] != '0' || (s[now] == '0' && lz))
35     {
36         y = dfs(now + 1, true, (mod + trans(now)) % 3) + 1;
37         if (y > x)
38         {
39             path[now][lz][mod] = 1;
40             return dp[now][lz][mod] = y;
41         }
42     }
43     return dp[now][lz][mod] = x;
44 }
45 
46 void get_path(int now, bool lz, int mod)
47 {
48     if (now == n)
49         return;
50     if (path[now][lz][mod])
51     {
52         ans[cnt++] = now;
53         get_path(now + 1, true, (mod + trans(now)) % 3);
54     }
55     else
56     {
57         get_path(now + 1, lz, mod);
58     }
59 }
60 
61 int main()
62 {
63     cin >> s;
64     n = s.length();
65     memset(dp, -1, sizeof(dp));
66     int tmp = dfs(0, false, 0);
67     if (tmp <= 0)
68     {
69         if (s.find("0") != string::npos)
70             puts("0");
71         else
72             puts("-1");
73     }
74     else
75     {
76         get_path(0, false, 0);
77         for (int i = 0; i < cnt; i++)
78         {
79             putchar(s[ans[i]]);
80         }
81         puts("");
82     }
83     return 0;
84 }
原文地址:https://www.cnblogs.com/wangyiming/p/6655067.html