【问题标题】:Wrong Answer in Online Judge (CODECHEF)在线裁判中的错误答案 (CODECHEF)
【发布时间】:2019-08-20 19:57:21
【问题描述】:

我一直在尝试解决 codechef 上的以下问题 https://www.codechef.com/problems/CHMOD

我期待一个时间限制错误,但它给了我一个错误的答案。虽然我找到了一种在时间限制的情况下解决它的方法,但无法弄清楚这个错误答案的原因。

这是我的解决方案

#include <stdio.h>
#include <string.h>

int main(void) {
    int num,i;
    scanf("%d",&num);
    int arr[num];
    for(i=0;i<num;i++){
        scanf("%d",&arr[i]);
    }
    int testCases,l,r;
    long int m,pro=1;
    scanf("%d",&testCases);
    while(testCases--){
        pro=1;
        scanf("%d%d%ld",&l,&r,&m);
        i=0;
        while(arr[i]!=l){
            i++;
        }
        while(arr[i]!=r){
            pro=(pro*arr[i])%m;
            i++;
        }
        pro=(pro*arr[i])%m;
        printf("%d\n",pro);
    }
    return 0;
}

【问题讨论】:

标签: c


【解决方案1】:

while(arr[i]!=l)while(arr[i]!=r) 是错误的。左侧和右侧的指标LiRi 是索引或计数,而不是数组中的值。你应该使用一个简单的for 循环:

for (i = l; i <= r; ++i)
    pro = pro * arr[i-1] % m;

请注意,索引是i-1,因为LiRi 使用从一开始的索引,但C 对其数组使用从零开始的索引。

【讨论】:

    【解决方案2】:

    由于您使用 C 来解决程序,您必须意识到问题描述假定数组索引从 1 而不是 0 开始。因此,您必须调整作为输入给出的左右段边界的值。只需从左侧值中减去 1 并从那里开始分段。在您的索引小于正确值时继续处理该段。 您对问题的理解有些缺陷。您需要将分段中的所有值相乘,然后取乘积的 mod。

    使用 Ada 查看以下解决方案:

    -----------------------------------------------------------------------
    -- Code Chef CHMOD
    -----------------------------------------------------------------------
    with Ada.Text_IO; use Ada.Text_io;
    with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
    
    procedure Chmod is
       subtype Num_Items is Positive range 1..100_000;
       subtype Values is Integer range 1..100;
       type Data_Array is array(Num_Items range <>) of Values;
       Num_Elements : Num_Items;
    begin
       Get(Num_Elements);
       declare
          Toy    : Data_Array(1..Num_Elements);
          Left   : Num_Items;
          Right  : Num_Items;
          Mi     : Positive;
          Games  : Num_Items;
          Result : Positive;
       begin
          for Num of Toy loop
             Get(Num);
          end loop;
          Get(Games);
          for I in 1..Games loop
             Result := 1;
             Get(Left);
             Get(Right);
             Get(Mi);
             for V in Left..Right loop
                Result := Result * Toy(V);
             end loop;
             Put(Item => Result mod Mi, Width => 1);
             New_Line;
          end loop;
       end;
    end Chmod;
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      相关资源
      最近更新 更多