文章

2

粉丝

135

获赞

3

访问

4.5k

头像
DFS模拟
P1264 北京大学机试题
发布于2023年3月8日 23:57
阅读数 2.6k

将n视为根 ,然后深搜算法,在每次递归时候进行检测是否超过了m;未超过则cnt+1;超过则返回;最后cnt即为结果

#include <iostream> 


using namespace std;
int n, m, cnt = 0;

typedef struct Mtree {
    int val;
    struct Mtree* ltree, * rtree;

} mtree;
mtree root1;
void dfs(mtree* rt, int val) {
    rt->val = val;
    if (val <= m) {
        cnt += 1;
        rt->ltree = new mtree;
        rt->rtree = new mtree;
    }
    else return;

    dfs(rt->ltree, val * 2);
    dfs(rt->rtree, val * 2 + 1);
}


int main() {
    while (scanf("%d%d", &n, &m) != EOF)
    {
        cnt = 0;
        mtree t1;
        dfs(&t1, n);
        printf("%d\n", cnt);
    }
}

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发