POJ - 3252 - Round Numbers(数位DP)

拥有回忆 提交于 2019-12-06 23:39:17

链接:

https://vjudge.net/problem/POJ-3252

题意:

The cows, as you know, have no fingers or thumbs and thus are unable to play Scissors, Paper, Stone' (also known as 'Rock, Paper, Scissors', 'Ro, Sham, Bo', and a host of other names) in order to make arbitrary decisions such as who gets to be milked first. They can't even flip a coin because it's so hard to toss using hooves.

They have thus resorted to "round number" matching. The first cow picks an integer less than two billion. The second cow does the same. If the numbers are both "round numbers", the first cow wins,
otherwise the second cow wins.

A positive integer N is said to be a "round number" if the binary representation of N has as many or more zeroes than it has ones. For example, the integer 9, when written in binary form, is 1001. 1001 has two zeroes and two ones; thus, 9 is a round number. The integer 26 is 11010 in binary; since it has two zeroes and three ones, it is not a round number.

Obviously, it takes cows a while to convert numbers to binary, so the winner takes a while to determine. Bessie wants to cheat and thinks she can do that if she knows how many "round numbers" are in a given range.

Help her by writing a program that tells how many round numbers appear in the inclusive range given by the input (1 ≤ Start < Finish ≤ 2,000,000,000).

思路:

转为二进制表示去DP,注意前缀0的处理。前缀0要减少有效长度。

代码:

// #include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<vector>
#include<string.h>
#include<set>
#include<queue>
#include<algorithm>
#include<math.h>
using namespace std;
typedef long long LL;
const int MOD = 1e9+7;
const int MAXN = 1e6+10;

LL F[40][40][40];
LL dig[40];
LL a, b;

LL Dfs(int pos, int cnt, bool zer, bool lim, int len)
{
    if (pos == -1)
        return cnt >= (len+1)/2;
    if (!lim && F[pos][len][cnt] != -1)
        return F[pos][len][cnt];
    int up = lim ? dig[pos]: 1;
    LL sum = 0;
    for (int i = 0;i <= up;i++)
    {
        if (i == 0 && !zer)
            sum += Dfs(pos-1, cnt+1, false, lim && i == up, len);
        else if (i == 0 && zer)
            sum += Dfs(pos-1, cnt, true, lim && i == up, len-1);
        else
            sum += Dfs(pos-1, cnt, false, lim && i == up, len);
    }
    if (!lim)
        F[pos][len][cnt] = sum;
    return sum;
}

LL Solve(LL x)
{
    int p = 0;
    while(x)
    {
        dig[p++] = x%2;
        x /= 2;
    }
    return Dfs(p-1, 0, true, true, p);
}

int main()
{
    // freopen("test.in", "r", stdin);
    memset(F, -1, sizeof(F));
    while(~scanf("%lld%lld", &a, &b))
    {
        printf("%lld\n", Solve(b)-Solve(a-1));
    }

    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!