標籤:
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 數學 + 思維題