CSES - Ferris Wheel
Authors: Danh Ta Chi Thanh, Kenny Cho, Nathan Gong
Since each gondola can contain either 1 or 2 children, for each gondola, we can do one of two things:
- Pair the lightest child with the heaviest child possible without exceeding the weight limit.
- If the pairing isn't possible, we only include the lightest child.
Those left unpaired each get their own gondola. The implementation below uses the above method.
Alternatively, for each gondola, we can also
- Pair the heaviest child with the lightest child if possible.
- Otherwise, only include the heaviest child.
Both pairing methods can be achieved in time using two pointers, and sorting brings the overall time complexity to .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int maxn = 2e5 + 10;// Variables used for the current problemint n, x, p[maxn], i, j, ans;// Keeps track of the number of children who have had their own gondolabool have_gondola_yet[maxn];
Java
import java.util.*;public class FerrisWheel {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int x = sc.nextInt();sc.nextLine();
Python
_, max_weight = map(int, input().split())weights = sorted(map(int, input().split()))light_ptr = 0heavy_ptr = len(weights) - 1gondola_total = 0while light_ptr <= heavy_ptr:# Pair the heaviest child with the lightest child if possibleif weights[light_ptr] + weights[heavy_ptr] <= max_weight:light_ptr += 1
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!