Problem Info
My Work
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* https://codeforces.com/problemset/problem/1359/C
* 3
* 30 10 20
* 41 15 30
* 18 13 18 should output 2, 7, and 1, each on a newline
*/
public final class WaterMix {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int testNum = Integer.parseInt(read.readLine());
for (int t = 0; t < testNum; t++) {
StringTokenizer info = new StringTokenizer(read.readLine());
int hot = Integer.parseInt(info.nextToken());
int cold = Integer.parseInt(info.nextToken());
int target = Integer.parseInt(info.nextToken());
if (cold > hot) {
throw new IllegalArgumentException("invalid water temperatures lol");
}
double closest = Math.abs(hot - target);
int cupNum = 1;
double avg = (double) (hot + cold) / 2;
if (Math.abs(avg - target) < closest) {
cupNum = 2;
closest = Math.abs(avg - target);
}
if (avg < target) {
int theoretical = (cold - hot) / (hot + cold - 2 * target);
int loOdd = (theoretical - 1) / 2 * 2 + 1;
double loOddTemp = ((double) (loOdd - 1) * (hot + cold) / 2 + hot) / loOdd;
if (Math.abs(loOddTemp - target) < closest) {
closest = Math.abs(loOddTemp - target);
cupNum = loOdd;
}
int hiOdd = loOdd + 2;
double hiOddTemp = ((double) (hiOdd - 1) * (hot + cold) / 2 + hot) / hiOdd;
if (Math.abs(hiOddTemp - target) < closest) {
cupNum = hiOdd;
}
System.out.println(loOddTemp + " " + hiOddTemp);
}
System.out.println(cupNum);
}
}
}
It’s an O(T) solution using some math voodoo. The thing is, it fails for this test case, where for
1
999977 17 499998
should output 499981, but my program outputs 499979.
However, I checked the average temperature for both, and they’re the same up to maximum precision.
How could I achieve greater precision?