c - 我的代码不适用于大输入

标签 c

问题陈述在这里https://www.interviewstreet.com/challenges/dashboard/#problem/4fe12e4cbb829

You are distributing candy among children. All the children sit in a line and each of
them  has a rating score according to his or her usual performance. Each child gets 
at least 1 piece. Children get jealous of their immediate neighbors, so if two 
children sit next to each other then the one with the higher rating must get 
more candies. You wants to save money, so minimize the total number of candies.

Input: A file with the children's ratings, 1 per line.

我的代码适用于较小的输入大小,但对于非常大的输入,它要么不提供任何输出(在 Interview.com 控制台上),要么在我的系统上与答案有少量偏差。 我的代码中有什么错误?

#include <stdio.h>

int main() 
{
    int i, j, n, rating[100000], candy[1000000], total = 0;

    scanf("%d", &n);

    for (i=0 ; i < n; i++) 
    {
        scanf("%d",&rating[i]);
        candy[i] = 1;
    }

    for (i=0 ; i < n+1 ; i++)
    {
      for (j=1 ; j < n-1; j++)
      {
          if( rating[j-1] < rating[j] )
          {
              if ( candy[j-1] >= candy[j] )
                  candy[j]++;
          }

          if( rating[j+1] < rating[j] )
          {
              if ( candy[j+1] >= candy[j] )
                  candy[j]++;
          }       
      }  
    }

    for (i=0 ; i < n ; i++)
        total = total + candy[i];

    printf("%d",total);

    return 0;
}

最佳答案

您可能会遇到使用自动数组 ratingcandy 实现的转换限制之一。尝试将它们放在文件范围内,即在 main 之外。然后它们有静态存储期限。大多数系统允许比自动对象大得多的静态对象。

关于c - 我的代码不适用于大输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12234886/

相关文章:

c++ - 从单独的线程发送 UDP

c - 从 RAM 执行代码时应该禁用中断吗?

html - 使用LoadRunner录制脚本

c - 我怎样才能在 ansi C90 中捕获运行时错误

c - 字符串与二维数组 C 比较

c++ - 将 C 与 C++ 链接是否可以避免在 C 中合法但在 C++ 中不合法的未定义行为?

c - 在Linux的net/ipv4/udp.c中,为什么UDP数据包需要通过xfrm4_policy_check()来处理?

c - 将数组类型分配给指针类型?

c - zlib 写入原始编码流

c - 如果 malloc 通过 gdb 返回 NULL,如何设置条件断点