java - SPOJ "ACPC10A - What’ s Next”-错误答案

标签 java algorithm math output

我已经尝试了以下代码,它与我尝试过的自定义输入配合得很好,但是,它没有被接受并显示 - 错误答案

SPOJ - https://www.spoj.com/problems/ACPC10A/

import java.util.*;
import java.lang.*;

class Main
{
    public static void findProgression(int a, int b, int c){
        int diff1 = Math.abs(b-a);
        int diff2 = Math.abs(c-b);
        int nextNumber;
        if(diff1 == diff2){
            nextNumber = c + diff1;
            System.out.println("AP " + nextNumber);
        }else{
            nextNumber = c*b/a;
            System.out.println("GP " + nextNumber);
        }
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        while(a != 0 || b != 0 || c != 0){
            findProgression(a,b,c);
            a = scan.nextInt();
            b = scan.nextInt();
            c = scan.nextInt();
        }       
    }
}

最佳答案

有几件事需要注意:

1)应该按原样比较差异,而不是绝对值。

2)计算GP的共同比率时要小心。使用类型转换。

3)解的破坏条件。

4) 整数溢出。

看看下面的实现:

import java.util.*;
import java.lang.*;

class Solution
{
    public static void findProgression(long a, long b, long c){
        long diff1 = b-a;
        long diff2 = c-b;
        long nextNumber;
        if(diff1 == diff2){
            nextNumber = c + diff1;
            System.out.println("AP " + nextNumber);
        }else{
            nextNumber = (long)((double)c*((double)c/(double)b));
            System.out.println("GP " + nextNumber);
        }
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner scan = new Scanner(System.in);

        while(true){

            int a = scan.nextInt();
            int b = scan.nextInt();
            int c = scan.nextInt();

            if(a==0 && b==0 && c==0)break;

            findProgression(a, b, c);

        }
    }
}

关于java - SPOJ "ACPC10A - What’ s Next”-错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61918561/

相关文章:

math - 乘法矩阵

c - 如何在没有溢出的情况下用定点运算计算多项式?

java - 在 Enfinity 中从 Pipeline 处理 AJAX 请求

java - Java中图连通性算法的通用实现

algorithm - 查找具有给定差异的对

c++ - 在示例问题中合并操作?

java - 具有最大间隙长度 3 的全局成对序列比对

r - rowSums(X %*% C * X) 的语义是什么

java - 在文件读取发生之前更改标签文本

java - 根据数组中找到的单词仅返回一个句子