cf Educational Codeforces Round 50 C. Classy Numbers

原題:
C. Classy Numbers
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Let’s call some positive integer classy if its decimal representation contains no more than 3 non-zero digits. For example, numbers 4, 200000, 10203 are classy and numbers 4231, 102306, 7277420000 are not.You are given a segment [L;R]
. Count the number of classy integers x such that L≤x≤R.

Each testcase contains several segments, for each of them you are required to solve the problem separately.

Input
The first line contains a single integer T (1≤T≤10^4) — the number of segments in a test case.

Each of the next T lines contains two integers Li and Ri (1≤Li≤Ri≤10^18).

Output
Print T lines — the i-th line should contain the number of classy integers on a segment [Li;Ri].

Example
input
4
1 1000
1024 1024
65536 65536
999999 1000001
output
1000
1
0
2

中文:

給你一個區間,讓你判斷這個區間當中整數中非零位不超過3個的數字的個數。

代碼:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

vector<ll> res;
int t;

void dfs(int pos,int cnt,ll cur)
{
    if(18==pos)
    {
        res.push_back(cur);
        return;
    }
    dfs(pos+1,cnt,cur*10);
    if(cnt<3)
    {
        for(ll i=1;i<=9;i++)
            dfs(pos+1,cnt+1,cur*10+i);
    }
}

int main() 
{
	ios::sync_with_stdio(false);
    dfs(0, 0, 0);
    res.push_back(1000000000000000000);

    cin>>t;
    while(t--)
    {
        ll L, R;
        cin>>L>>R;
        cout<<upper_bound(res.begin(), res.end(), R) - lower_bound(res.begin(), res.end(), L)<<endl;
    }
    return 0;
}

解答:

這是純的排列組合計數問題,大概思路是,可以先通過算出整10次冪之內有多少個滿足條件的數,然後從左向右,每次在後面的位數當中選3位置、選2個位置、選1個位置以及選0個位置添加非0位,自己推了個計數公式,算的漏洞百出。-_-!!!

官方題解中給出了一種特別輕鬆的解決方法,就是暴力把所有數枚舉一遍,然後使用二分查找兩個區間端點即可,太簡單了,可惜自己當時就顧着算公式,沒想到這辦法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章