UVa 11384 - Help is needed for Dexter 分析, 树状数组 难度: 0

本文解析了UVA在线评测系统中编号为11363的问题,即如何通过最少步骤将序列[1,..,n]中的所有数减至0。采用树状数组思想,利用log2(n)的特性,实现了一种高效算法。代码使用C++实现,详细介绍了mylog函数用于计算所需步数。

题目

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2379


题意

[1, .., n],每次可以减一个1-n之间的数,问至少多少次能将全部数字减为0(减为0后不再变化)

 

思路

如刘书思路。

想到1...n,就会想到树状数组分bit存储的思想,进而就会觉得分bit减是一个想法。因为log2(n) <= (x - 1)logx(n), 此处x大于等于3,所以可以认为答案就是结果的bit长度。

 

感想

1. 三倍ice cream!

 

代码

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <tuple>
#include <set>
#include <map>
#include <cassert>
#define LOCAL_DEBUG
using namespace std;

int mylog(int n) {
    int x, bit;
    x = 1;
    bit = 0;
    while (x <= n) {
        x <<= 1;
        bit++;
    }
    return bit;
}

int main() {
#ifdef LOCAL_DEBUG
    freopen("input.txt", "r", stdin);
    //freopen("output2.txt", "w", stdout);
#endif // LOCAL_DEBUG
    int n;
    for (int ti = 1; scanf("%d", &n) == 1; ti++) {
        printf("%d\n", mylog(n));
    }

    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/xuesu/p/10370996.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值