[字符串]

题目:给出一个整数n,问1-n之间包括n在内的所有数中49出现的次数。

输入首先为一个整数T,表示接下来有T组输入。

# include <cstdio>
# include <cstring>

# define N 10000000
# define LEN 22

typedef long long int LL;

LL f[LEN][10];
LL pow10[LEN];

void init(void)
{
    pow10[0] = 1;
    for (int i = 1; i < LEN; ++i)
    {
        pow10[i] = 10*pow10[i-1];
        if (i>=2)f[i][1] = (i-1)*pow10[i-2];
     }           

    memset(f[0], 0, sizeof(f[0]));
    f[1][1] = 0;
    for (int i = 1; i < LEN; ++i)
    for (int j = 1; j < 10; ++j)
    {
        f[i][j] = f[i][j-1]+f[i][1]+(j==5 ? pow10[i-1]:0);
     }       
}

int compute(int num)
{
    int fact = 1;
    LL ret = 0;
    LL x = num;
    while (x)
    {
        int t = x % 10;
        ret += f[fact-1][t];
        ++fact;
        x/=10;
    }
    x = num, fact = 1;
    while (x)
    {        
        if (x%100 == 49) ret+=num%fact+1, fact*=100, x/=100;
        else x/=10, fact*=10;
    }
    return ret;
}

int main()
{
    LL T;
    LL x;
    
    init();
    scanf("%I64d", &T);
    while (T--)
    {
        scanf("%I64d", &x);
        printf("%I64d\n", compute(x));
    }

    return 0;
}

/*

可以对比这两道题的差异:http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?cid=1432&pid=1002&ojid=0

*/

posted on 2012-08-01 23:44  getgoing  阅读(151)  评论(0编辑  收藏  举报

导航