4 / 4
Jul 2012

Question : spoj.pl/problems/GSS1/
First , it was giving TLE in 9th test case when scanf is used .
After changing scanf to getchar , it's giving wrong answer . And also , Confirm me please that whether should I give the -ve ans or zero for [color=#000080]-ve array[/color] ? confused question
I've tried for both cases but still showing wrong ans .
Complexity is O(n) .

#include<stdio.h>
#include<stdlib.h>
#define max(x,y) (x>y?x:y)
int main()
{
    long t=0,i=0,m=0,c,q=0;
    while((c=getchar())!='\n')
         t=t*10+c-'0';
    long an[t];
    for(i=0;i<t;i++)
         an[i]=0;
    i=0;     
    while(i<t)
    {     
         c=getchar();
         if(c=='\n')   break;
         if(c=='-') 
              q=1;
         else if(c==' ')
             { 
               if(q) an[i]*=-1;
               q=0;i++;
             }
         else an[i]=an[i]*10+c-'0';
    }
    if(q)  an[i]*=-1;
    while((c=getchar())!='\n')
         m=m*10+c-'0';
    while(m--)
    {
         long a=0,b=0,k=2,p=0;
         long s=0L;c=0;
         while((c=getchar())!=' ')
         {
               a=a*10+c-'0';         
         }
         while((c=getchar())!='\n')
         {
                b=b*10+c-'0';         
         }
         long s1=0,n=0, min=an[a-1];
         for(i=a-1;i<b;i++)
         {   if(an[i]<0)
                  min=(an[i]>min)?an[i]:min;
             else { n=1;break;}
         }
         if(!n)   s1=min;      // If all nums are -ve , then s1 =0 (if want to ) else s1=min  (means min(-ve))   
         else 
         for(i=a-1;i<b;i++)
         {         
              s+=an[i];
              if(s<0)
                 s=0;
              else if(s1<s)
                 s1=s;
         }    
         printf("%ld\n",s1);
    }
    return 0;
}
  • created

    Jul '12
  • last reply

    Jul '12
  • 3

    replies

  • 345

    views

  • 2

    users

  • 2

    links

en.m.wikipedia.org/wiki/Newline1
After reading this you should realize why using getchar in this fashion is a bad idea. Getchar can be useful but it involves a lot of extra work to use accurately. I usually use scanf instead.

As for your TLE. Your complexity for each query is O(n). Unfortunately you don't know the constraint on M, but that should be a huge red flag saying that it might be very large. O(n*m) will not pass the timelimit. Scanf is not the cause of the TLE.

To your question about the negative array. What do you think the answer should be? Back it up with proof from the problem statement.

Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }

acc to the above statement , ans can be -ve . But i've read some comments. Some are saying zero and some are -ve .
But i've tried both the cases .
The thing is what should i do for TLE ???

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 14 7d

Want to read more? Browse other topics in C and C++ or view latest topics.