Warehouse
Autumn Tournament (2009)
Submission name: sklad.cpp
Problem summary
A warehouse contains n tonnes of sugar, flour, rice, and salt. Sugar and flour have equal quantities. Exactly k tonnes are neither rice nor salt, and m tonnes are neither sugar nor salt. Find the quantity of salt.
Source clarification. The input quantities n, k, m are integers, but the statement does not say that the individual goods have integral weights; the solution preserves half-tonne answers exactly.
Input
Three integers n, k, m.
Output
The quantity of salt in tonnes.
Constraints
1 ≤ k, m < n ≤ 1000; the quantities describe the stated warehouse.
Worked example
Original statement sample.
Input
50 36 24
Output
8
Solution analysis
- The k tonnes are sugar plus flour. Since those quantities are equal, each is k/2 tonnes.
- The m tonnes are flour plus rice. Thus sugar, flour, and rice together weigh m + k/2, leaving n − m − k/2 tonnes of salt. Compute twice this quantity as 2n − 2m − k to retain exact halves.
- For n = 50, k = 36, and m = 24, sugar and flour each weigh 18 tonnes. Rice weighs 6 tonnes and salt weighs 50 − 18 − 18 − 6 = 8 tonnes.
Why it works
Equal sugar and flour quantities and their total k imply sugar = flour = k/2. The non-salt total is sugar + (flour + rice) = k/2 + m. Subtracting this from n therefore gives exactly the salt quantity.
Watch out. Do not truncate k/2 before subtraction when k is odd. The source does not require the four quantities themselves to be integral.
Commented C++17 solution
An independently written complete program with standard headers.
#include<algorithm>
#include<iostream>
#include<limits>
#include<string>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int total,sugarAndFlour,flourAndRice;
cin>>total>>sugarAndFlour>>flourAndRice;
// Keep twice the answer to represent half-tonnes exactly.
int twiceSalt=2*total-2*flourAndRice-sugarAndFlour;
cout<<twiceSalt/2;
if(twiceSalt%2!=0){
cout<<".5";
}
cout<<'\n';
}