我的代码不适合大输入

时间:2012-09-02 09:38:59

标签: 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;
}

1 个答案:

答案 0 :(得分:0)

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