Codeforces Beta Round #91 (Div. 2 Only)深度优先

来源:互联网 发布:ddos网络层攻击 编辑:程序博客网 时间:2024/06/07 09:52

C. Lucky Sum

对这道题我想了很多方法,最直观的方法是打表法,把要用的数直接打表存起来,然后直接查找就好。算法思路是对的,但是提交的时候一直提示不是时间超时就是占用内存太大,最后看到了别人的代码竟然采用了深度优先搜索的办法给解决了。我对深度优先里的递归一直理解的都不怎么好,先整理下来有时间再看吧。代码如下:

//the code is not written by myself#include <iostream>#include<algorithm>#define LL long longusing namespace std;const int maxn = 20000;LL d[maxn];int tot = 1;void dfs(LL num, int cur) {d[tot++] = num;if (cur > 11) return;dfs(num * 10 + 4, cur + 1);dfs(num * 10 + 7, cur + 1);}LL sum(LL x) {if (x == 0) return 0;LL temp = 0;for (int i = 1; i < tot; i++){if (x >= d[i])temp += d[i] * (d[i] - d[i - 1]);else {temp += d[i] * (x - d[i - 1]);break;}}return temp;}int main() {dfs(4, 0);dfs(7, 0);sort(d + 1, d + tot);LL lt, rt;cin >> lt >> rt;cout << sum(rt) - sum(lt - 1) << endl;return 0;}


0 0
原创粉丝点击