CP: Cutting ropes

You have n ropes of different lengths and want k pieces that all have the same whole length. You may cut ropes but not join them. Find the longest length that gives at least k pieces.

What to build

Binary search the piece length L from 1 to the longest rope. For a given L, each rope gives rope / L pieces; add them up and check that the total is at least k.

Requirements

  • Use binary search on the length
  • Print 0 if even length 1 does not give k pieces

Input

The first line has n and k. The second line has the n rope lengths.

Output

The longest whole piece length, or 0.

Constraints

1 ≤ n ≤ 100,000. 1 ≤ k ≤ 10⁹. Lengths are from 1 to 10⁹.

Example

Input:

4 11
802 743 457 539

Output:

200

Why it works

If pieces of length L are enough, pieces of any shorter length are enough too, so the good lengths form a range that starts at 1. The check is one pass that sums rope / L. Binary search finds the largest good length in about 30 checks.

Examples

Example 1 · Input
4 11
802 743 457 539
Expected output
200
Example 2 · Input
3 5
4 4 4
Expected output
2

Hints

Hint 1

works(L): the sum of rope / L over all ropes is at least k. Use long long for the sum.

Hint 2

lo = 0, hi = the longest rope. mid = lo + (hi - lo + 1) / 2.

Hint 3

If works(mid) then lo = mid, else hi = mid - 1. The answer is lo (0 if nothing works).

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long k;
    cin >> n >> k;
    vector<long long> rope(n);
    long long longest = 0;
    for (auto& x : rope) {
        cin >> x;
        if (x > longest) longest = x;
    }
    long long lo = 0, hi = longest;
    while (lo < hi) {
        long long mid = lo + (hi - lo + 1) / 2;
        long long pieces = 0;
        for (long long r : rope) pieces += r / mid;
        if (pieces >= k) lo = mid;
        else hi = mid - 1;
    }
    cout << lo << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Binary search on the answer →