Algoogle

Algorithm for Programming Contest

AOJ 2441 FizzBuzz

Category: AOJ Tag: binary-search, math

FizzBuzz

問題概要


解法


まずs文字目の数の桁数を求める.
各桁数の区間の文字数は
桁数×(その桁数の3の倍数と5の倍数以外の数)+4*(3の倍数と5の倍数の数)
で求められ, sを超えるまで計算すればいい
桁数を求めたら, その桁数の区間について2分探索でs文字目の数を探す.

コード


(2441.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a) for(int i = 0;i < (a); i++)
typedef long long ll;

string ntos(ll num){
    string ret = "";
    while(num){
        int t = num % 10;
        ret += (t + '0');
        num /= 10;
    }
    reverse(all(ret));
    return ret;
}

int main(){
    ll s;
    cin >> s;
    ll pret = 0, len = 0;
    int dig;
    repi(i,1,18){
        ll t = pow(10.0,i)-1;
        ll l = i*(t-t/3-t/5+t/15-pret+pret/3+pret/5-pret/15)+4*(t/3+t/5-pret/3-pret/5);
        if(len+l<s) len += l;
        else {
            dig = i;
            break;
        }
        pret = t;
    }
    ll lb = pret+1, ub = lb*10-1;
    ll m, mlen;
    while(lb < ub){
        m = (lb + ub) / 2;
        mlen = len + dig*(m-m/3-m/5+m/15-pret+pret/3+pret/5-pret/15)+4*(m/3+m/5-pret/3-pret/5);
        if(mlen > s) ub = m - 1;
        else if(mlen < s) lb = m + 1;
        else {
            lb = m;
            ub = m;
        }
    }
    ll t = lb;
    mlen = len + dig*(lb-lb/3-lb/5+lb/15-pret+pret/3+pret/5-pret/15)+4*(lb/3+lb/5-pret/3-pret/5);
    if(!(lb % 3)) mlen -= 4;
    if(!(lb % 5)) mlen -= 4;
    if(lb%3 && lb%5) mlen -= dig;
    ll w = s - mlen;
    string ans = "";
    ll cur = lb;

    while(ans.size() <= 20 + w){
        if(!(cur % 3)) ans += "Fizz";
        if(!(cur % 5)) ans += "Buzz";
        if(cur%3 && cur%5) ans += ntos(cur);
        cur++;
    }
    rep(i,20) cout << ans[i+w-1];
    cout << endl;
    return 0;
}

Comments