UVa 11384 Help is needed for Dexter 正整数序列

来源:互联网 发布:openwrt网络尖兵 编辑:程序博客网 时间:2024/05/19 03:29

题意:给定正整数N,要求对序列1、2、3 ...... n 进行如下操作:选择若干个数,令它们同时减去一个正整数。求最少的操作步数,使得所有的数都变为0




水题。试几下就发现答案了。设最少的步数为 f(n),则答案为 f(n/2) + 1。实际上可以证明这个答案。很显然,f(n)是个递增序列(不一定严格)。我们每操作一次时,肯定是选择连续若干个数进行操作,如果断续的话就令选的数连续,多选一些数操作肯定不会令答案更大。操作后,其实只需要留下不同的数字(相同的数可以一起操作),且这些数字肯定仍是一个连续的序列,于是可以设f(n) = f(x) + 1,其中x < n。于是我们希望操作一次后x尽量小。假设我们不选n/2,那么操作后 x >= n/2,如果选了,那么每个数最多只能减去n/2,而最大的数n - n/2后至少为n/2,也就是说操作一次后x至少为n/2,于是我们就取x = n/2,这样每次操作的时候选择n/2 ~ n,令它们同时减去n/2即可。于是答案为f(n) = f(n/2) + 1。




#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <algorithm>#include <stack>#include <queue>#include <vector>#include <map>#include <set>using namespace std;int main(){    int n;    while(scanf("%d", &n) != EOF)    {        int ans = 0;        for(; n > 0; n /= 2)            ans++;        printf("%d\n", ans);    }    return 0;}


0 0