无法理解这种对在线法官的解决方案可能是错误的

时间:2018-10-27 21:19:15

标签: java

Here is the question from the online judge

我正在尝试解决一个似乎相对简单的问题,假设输入了孩子的数量,并且有糖果的总数,如果可以在孩子之间平均分配糖果,则打印“是”,否则打印“不”。

从图像中可以看到,前两个测试用例通过了,最后一个没有通过。我在这里挠头,有什么想法吗?

enter image description here

import java.util.*;
public class AnotherCandies {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int cases = sc.nextInt();

        for(int i = 0; i < cases; i++)
        {
            long numKids = sc.nextLong();
            long total = 0;

            for(int j = 0; j < numKids; j++)
            {
                long n = sc.nextLong();
                total += n;
            }

            if(total % numKids == 0)
                System.out.println("YES");
            else
                System.out.println("NO");
        }

    }

}

2 个答案:

答案 0 :(得分:1)

长时间过载总和有问题。您可以在每个步骤中使用%,然后再次使用它来获得最终的总和:

public static void main(String[] args) {
    try (Scanner scan = new Scanner(System.in)) {
        for (int i = 0, T = scan.nextInt(); i < T; i++) {
            int N = scan.nextInt();
            int sum = 0;

            for (int j = 0; j < N; j++)
                sum = (int)(scan.nextLong() % N + sum) % N;

            System.out.println(N == 0 ? "YES" : "NO");
        }
    }
}

enter image description here

答案 1 :(得分:-2)

我认为您需要检查案例total=0。也许是这样,你应该打印否?

if(total == 0)
     System.out.println("NO");
else if(total % numKids == 0)
     System.out.println("YES");
else
     System.out.println("NO");