0

问题陈述在这里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;
}
4

1 回答 1

0

您可能会遇到使用自动数组ratingcandy. 尝试将它们放在文件范围内,即main. 然后它们具有静态存储持续时间。大多数系统允许比自动对象大得多的静态对象。

于 2012-09-02T10:21:56.340 回答