【33.33%】【codeforces 552B】Vanya and Books

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.

Vanya wants to know how many digits he will have to write down as he labels the books.

Input
The first line contains integer n (1?≤?n?≤?109) — the number of books in the library.

Output
Print the number of digits needed to number all the books.

Examples
input
13
output
17
input
4
output
4
Note
Note to the first test. The books get numbers 1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13, which totals to 17 digits.

Note to the second sample. The books get numbers 1,?2,?3,?4, which totals to 4 digits.

【题目链接】:http://codeforces.com/contest/552/problem/B

【题解】

1..9都是1个数字+9
10..99都是2个数字+(99-10+1)*2
100..999都是3个数字+….
字符串表示的数字为x,可以在字符串后面不断加数字9;组成的数字为y;然后记录当前加了几个9->len
则答案递增len*(y-x);
重复上述过程直到x<=数字n,且y>n;
然后剩下的数字都是和n的位数一样的.
则再递增(n-x)*len;

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

//const int MAXN = x;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);

int n;
LL ans = 0;
string now;

LL cl(string x)
{
    int len = x.size();
    LL now = 0;
    rep1(i,0,len-1)
        now = now*10+x[i]-'0';
    return now;
}

int main()
{
    //freopen("F:\rush.txt","r",stdin);
    rei(n);
    now = "0";
    int len = 1;
    LL pre = 0;
    while (1)
    {
        LL key = cl(now+"9");
        if (key <= n)
        {
            ans+=(key-pre)*len;
            len++;
            now+="9";
        }
        else
            break;
        pre = key;
    }
    if (pre==n)
        cout << ans <<endl;
    else
    {
       // cout << ans <<endl;
       // cout << len<<endl;
       // cout << pre<<endl;
        ans+=len*(n-pre);
        cout << ans<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626831.html