UVA 1363

來源:互聯網
上載者:User

UVA 1363 - Joseph's Problem

題目連結

題意:給定n, k,求出∑ni=1(k mod i)

思路:由於n和k都很大,直接暴力是行不通的,然後在紙上畫了一些情況,就發現其實對於k/i相同的那些項是形成等差數列的,於是就可以把整個序列進行拆分成[k,k/2],[k/2, k/3], [k/3,k/4]...k[k/a, k/b]這樣的等差數列,利用大步小步演算法思想,這裡a枚舉到sqrt(k)就可以了,這樣就還剩下[1,k/a]的序列需要去枚舉,總時間複雜度為O(sqrt(k)),然後注意對於n大於k的情況,n超過k的部分全是等於k,為(n - k) * k,這樣把所有部分加起來就是答案

這有一篇比較詳細的題解

代碼:

#include <stdio.h>#include <string.h>#include <math.h>long long n, k;long long solve() {    long long ans = 0;    if (n > k) ans += (n - k) * k;    long long a = (long long )sqrt(k), b = k / a;    for (long long i = a; i > 1; i--) {long long a0 = k / i, an = k / (i - 1);if (a0 > n) break;if (an > n) an = n;ans += (k % an + k % (a0 + 1)) * (an - a0) / 2;    }    for (int i = 1; i <= n && i <= b; i++) ans += k % i;    return ans;}int main() {    while (~scanf("%lld%lld", &n, &k)) {printf("%lld\n", solve());    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.