Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
4
Indexable
Never
import java.util.Scanner;

public class MagneticBalance {
    static final double EPSILON = 1e-10;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int test_case = 1; test_case <= T; test_case++) {
            int N = scanner.nextInt();
            double[] x = new double[N];
            double[] mass = new double[N];
            double totalMass = 0;

            for (int i = 0; i < N; i++) {
                x[i] = scanner.nextDouble();
                mass[i] = scanner.nextDouble();
                totalMass += mass[i];
            }

            double left = 0.0;
            double right = x[N - 1];
            double result = 0.0;

            while (right - left > EPSILON) {
                double mid = (left + right) / 2;
                double leftForce = 0;
                double rightForce = 0;

                for (int i = 0; i < N; i++) {
                    double dist = x[i] - mid;
                    if (dist < 0) {
                        leftForce += mass[i] * totalMass / (dist * dist);
                    } else {
                        rightForce += mass[i] * totalMass / (dist * dist);
                    }
                }

                if (leftForce < rightForce) {
                    left = mid;
                } else {
                    right = mid;
                }
                result = mid;
            }

            System.out.printf("#%d %.10f%n", test_case, result);
        }
    }
}