The value of will be in range . We will do a binary search on the value of .
Binary search works because for a particular value of , if we have then for all other , will also hold.
Now, how do we calculate the loss for a particular value of ?
The judge solution uses a Minimum-cost-maximum-flow network.
The flow of the network represents the number of days successfully served, and the cost represents the total loss.
As we need to serve every day, the flow in our network should be equal to the number of days and the cost should be no more than .
The network:
Let be the source of the network and be the sink.
Now for each day ,
If this is the first time book of type occurred, We add an edge from source to with flow = and cost = and another edge from to sink with flow = and cost = . Here . This means we must buy the book as we didn't buy that before and as we bought it we will sell it sometime.
If this is not the first time book of type occurred, let’s say on the 'th day book occurred last time, We add an edge from source to with flow = and cost = , another edge from to with flow = and cost and another edge from to sink with flow = and cost = . This represents the situation that we decided to sell the book the last time we had and buy the book again.
Now for each in range , we add an edge from node to node with flow = and cost = . This handles storing previously bought books on the shelves. The flow value is here, because it can be shown there exist at least one optimal strategy where you buy no more than one book on any of the nights.