Stone Division, Revisited

  • + 0 comments

    C++

    typedef long long llong;
    llong stoneDivision(llong n, vector<llong> const& s, size_t i = 0)
    {
        static unordered_map<llong, llong>* memo;
        if (!memo) {
            auto s1 = s;
            sort(s1.begin(), s1.end(), greater<llong>());
            memo = new unordered_map<llong, llong>();
            llong d = stoneDivision(n, s1);
            delete memo; memo = NULL;
            return d;
        }
        llong d = 0, key = (n << 10) | i;
        auto it = memo->find(key);
        if (it != memo->end()) return it->second;
        for (; i < s.size(); i++)
            if (n > s[i] && n % s[i] == 0)
                d = max(d, 1 + n / s[i] * stoneDivision(s[i], s, i));
        return ((*memo)[key] = d);
    }