CF792C Divide by Three
Posted 王宜鸣
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于CF792C Divide by Three的主要内容,如果未能解决你的问题,请参考以下文章
CodeForces 792C - Divide by Three [ 分类讨论 ]
codeforces 792C. Divide by Three
Codeforces977D ---Divide by three, multiply by two 深搜+map存出现的数
Divide by three, multiply by two CodeForces - 977D (思维排序)