Tuesday, November 12, 2019

UVa 1388 - Graveyard

// UVa 1388 - Graveyard

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextInt()) {
            int Nb = scanner.nextInt(); // number of statues at the beginning
            int Nadd = scanner.nextInt(); // statues to add
            int Ne = Nb + Nadd; // number of statues at the end

            BigDecimal Cb = BigDecimal.valueOf(10000).divide(BigDecimal.valueOf(Nb), MathContext.DECIMAL128);
            BigDecimal Ce = BigDecimal.valueOf(10000).divide(BigDecimal.valueOf(Ne), MathContext.DECIMAL128);

            BigDecimal allMovement = BigDecimal.ZERO;

            for (int i = 1; i < Nb; i++) {
                BigDecimal location = Cb.multiply(BigDecimal.valueOf(i));
                BigDecimal destination = location.divide(Ce, MathContext.DECIMAL128).setScale(0, RoundingMode.HALF_UP).multiply(Ce);
                BigDecimal movement = destination.subtract(location).abs();
                allMovement = allMovement.add(movement);
            }

            System.out.printf("%.4f\n", allMovement);
        }
    }
}
/*

for the i-th statue
its location is
  i*Cb
its destination is
  round(i*Cb / Ce) * Ce
so its movement is
  abs(round(i*Cb / Ce) * Ce - i*Cb)

Cb = 10,000 / Nb where Nb = number of statues at the beginning
Ce = 10,000 / Ne where Ne = number of statues at the end

sol = sum of abs(round(i*Cb / Ce) * Ce - i*Cb) for all i=0..Nb

*/

No comments:

Post a Comment