Bonetrousle HackerRank 數學 + 思維題

來源:互聯網
上載者:User

標籤:

https://www.hackerrank.com/contests/world-codesprint-6/challenges/bonetrousle

給定一個數n,和k個數,1--k這k個,要求選擇b個數,使得這b個數的和等於n。

首先考慮最小值,在1--k中選擇前b個數,是最小的,記為mi。最大值,後b個數相加,記為mx

注意到一個東西:如果mi <= n <= mx。那麼是絕對可行的。因為mi總能增加1(同時保證滿足要求),所以在這個區間裡面的,都是可行解。

所以首先從mi開始枚舉,每次把第B個數變成最大值k(第b - 1個數改成k - 1....依次類推,因為不能重複用數字)

則總能枚舉到mi >= n。然後輸出方案即可。

bug點:後b個數太大了,會爆LL。所以,當後面的數相加到 >= n的時候,夠了,證明n是 <= mx的了,有可行解。

然後對著類比即可。複雜度O(b)

#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>using namespace std;#define inf (0x3f3f3f3f)typedef long long int LL;#include <iostream>#include <sstream>#include <vector>#include <set>#include <map>#include <queue>#include <string>const int maxn = 1e5 + 20;LL a[maxn];void work () {//    ios::sync_with_stdio(false);    LL n, k, b;//    scanf ("%lld%lld%lld", &n, &k, &b);    cin >> n >> k >> b;    //cout << n << " " << k << " " << b << endl;    LL mi = 0, mx = 0;    for (int i = 1; i <= b; ++i) {        mi += i;    }    for (LL i = k; i >= k - b + 1; --i) {        mx += i;        //if (mx < 0) while (1);        if (mx >= n) break; // ok    }    //cout << mi << " " << mx << endl;    if (mx < n) {        printf ("-1\n");        return ;    }    if (mi > n) {        printf ("-1\n");        return ;    }    LL now = mi;    int to = b;    LL get = k;    for (int i = 1; i <= b; ++i) a[i] = i;    while (true) {        now = now - a[to] + get;        a[to] = get;        if (now >= n) {            LL cut = now - n;            a[to] -= cut;            for (int i = 1; i <= b - 1; ++i) {                printf ("%lld ", a[i]);            }            printf ("%lld\n", a[b]);            break;        }        to--;        get--;    }}int main (){#ifdef LOCAL    freopen("data.txt","r",stdin);#endif    int t;    cin >> t;//    cout << t << endl;    while (t--) work ();    return 0;}
View Code

 

Bonetrousle HackerRank 數學 + 思維題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.