import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;
public class ForkJoinAverage {
    private static class AverageTask extends RecursiveTask<Long> {
        private final int[][] matrix;
        private final int startRow;
        private final int endRow;

        AverageTask(int[][] matrix, int startRow, int endRow) {
            this.matrix = matrix;
            this.startRow = startRow;
            this.endRow = endRow;
        }

        @Override
        protected Long compute() {
            if (endRow - startRow <= 10) {
                long sum = 0;
                for (int i = startRow; i < endRow; i++) {
                    for (int j = 0; j < i; j++) {
                        sum += matrix[i][j];
                    }
                }
                return sum;
            } else {
                int mid = (startRow + endRow) / 2;
                AverageTask left = new AverageTask(matrix, startRow, mid);
                AverageTask right = new AverageTask(matrix, mid, endRow);
                left.fork();
                long rightResult = right.compute();
                long leftResult = left.join();
                return leftResult + rightResult;
            }
        }
    }

    public static double calculate(int[][] matrix) {
        ForkJoinPool pool = new ForkJoinPool();
        long totalSum = pool.invoke(new AverageTask(matrix, 0, matrix.length));
        int totalCount = matrix.length * (matrix.length - 1) / 2;
        return (double) totalSum / totalCount;
    }
}
