Machine Works

Time limit2sMemory limit128 MB

Summary
Buy and resell at most one machine at a time over D days, each machine usable from its sale day, to maximize final cash.
Level

Hard8 of 10

Topics
Dynamic programming, Sorting, Binary search, Greedy
Solved
No attempts yet

Problem

You are the director of Arbitrarily Complex Machines (ACM for short), a company that produces advanced machinery using even more advanced machinery. The old production machinery has broken down, so you need to buy new production machines. Your goal is to make as much money as possible during the restructuring period. During this period you can buy and sell machines and operate them for profit while ACM owns them. Because of space restrictions, ACM can own at most one machine at a time.

During the restructuring period there will be several machines for sale. Being an expert in the advanced-machine market, you already know the price PiP_i and the availability day DiD_i of each machine MiM_i. Note that if you do not buy machine MiM_i on day DiD_i, then someone else will, and it will not be available later. You cannot buy a machine if ACM has less money than its price.

If you buy machine MiM_i on day DiD_i, then ACM can operate it starting on day Di+1D_i + 1. Each day the machine operates, it produces a profit of GiG_i dollars.

You may sell a machine to reclaim part of its purchase price on any day after you bought it. Each machine has a resale price RiR_i for which it may be sold back to the market. You cannot operate a machine on the day you sell it, but you may sell a machine and use the proceeds to buy a new machine on the same day.

Once the restructuring period ends, ACM sells any machine it still owns. Your task is to maximize the amount of money ACM makes during the restructuring.

Input

The input consists of several test cases. Each test case starts with a line containing three positive integers NN, CC, and DD: NN is the number of machines for sale (N≤105N \le 10^5), CC is the number of dollars ACM starts with (C≤109C \le 10^9), and DD is the number of days the restructuring lasts (D≤109D \le 10^9).

Each of the next NN lines describes one machine for sale with four integers DiD_i, PiP_i, RiR_i, and GiG_i: the day the machine is for sale, the price to buy it, the price for which it may be resold, and the daily profit from operating it. These satisfy 1≤Di≤D1 \le D_i \le D, 1≤Ri<Pi≤1091 \le R_i < P_i \le 10^9, and 1≤Gi≤1091 \le G_i \le 10^9.

The last test case is followed by a line containing three zeros.

Output

For each test case, display its case number followed by the largest number of dollars ACM can have at the end of day D+1D + 1. Print it in the form Case X: Y, where XX is the test case number (starting from 1) and YY is that largest number of dollars.

Examples1

  1. Example 1

    Input
    6 10 20
    6 12 1 3
    1 9 1 2
    3 2 1 2
    8 20 5 4
    4 11 7 4
    2 10 9 1
    0 0 0
    
    Expected output
    Case 1: 44