Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Greedy

Two City Scheduling

Medium · Greedy · Asked at Bloomberg, Amazon, Google

2m people will be interviewed; flying person i to city A costs a[i] and to city B costs b[i]. Exactly m people must go to each city. Print the minimum total cost.

Input

First line: 2m. Next 2m lines: a[i] b[i].

Output

The minimum total cost.

Constraints

Send everyone to B first, then choose who switches to A: switching person i changes the cost by a[i] − b[i]. Pick the m people with the smallest differences.

Example 1

Input

4
10 20
30 200
400 50
30 20

Output

110

Example 2

Input

2
5 5
1 100

Output

6

Hints

  1. Imagine everyone flies to B first.
  2. Moving person i to A changes the total by a[i] − b[i].
  3. You must move exactly half of them — pick the cheapest changes.

Approach

Sort people by a[i] − b[i] ascending. The first half go to A, the rest to B. Every assignment with m people in A costs (sum of b) + (sum of the chosen differences), so choosing the m smallest differences is optimal.

Complexity: O(n log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<pair<long long, long long>> p(n);
    for (auto &x : p) cin >> x.first >> x.second;
    sort(p.begin(), p.end(), [](auto &x, auto &y) { return x.first - x.second < y.first - y.second; });
    long long total = 0;
    for (int i = 0; i < n; i++) total += i < n / 2 ? p[i].first : p[i].second;
    cout << total << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
people = sorted(((data[1 + 2 * i], data[2 + 2 * i]) for i in range(n)), key=lambda x: x[0] - x[1])
print(sum(a for a, _ in people[: n // 2]) + sum(b for _, b in people[n // 2 :]))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[][] p = new long[n][2];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            p[i][0] = (long) in.nval;
            in.nextToken();
            p[i][1] = (long) in.nval;
        }
        Arrays.sort(p, (x, y) -> Long.compare(x[0] - x[1], y[0] - y[1]));
        long total = 0;
        for (int i = 0; i < n; i++) total += i < n / 2 ? p[i][0] : p[i][1];
        System.out.println(total);
    }
}

Solve Two City Scheduling online · All practice problems