Chef and work

using namespace std;
int main(){
  int n,k,t;
  cin>>t;
  while(t--){
    cin>>n>>k;
    int a[n];
    int sum=0,ans=0;
    for(int i=0;i<n;i++)
    {
      cin>>a[i];
      sum+=a[i];
      if(a[i]>k)
      {
        ans=-1;
        break;
      }
    //   if(sum==k)
    //   {
    //     ans++;
    //     sum=0;
    //   }
      if(sum>k)
      {
        ans++;
        sum=a[i];
      }
    }
   //
    if(ans==-1)
      cout<<-1<<endl;
    else
    {
       if(sum>0)
      cout<<ans+1<<endl;
      else cout<<ans<<endl;
    }
  }
}

why is my code not getting accepted

Never use a break statement while taking input.
Lets take an example

2
4 6
2 3 7 5
3 5
1 2 3
Here in first test case when you will encounter 7 at 2nd position(0-based indexing) your loop will break.
and 5 will be treated as n for second test case. so this will lead to incorrect input.

first take the input and then perform any other operations.

At least give quetion link man.

1 Like

Always post the link of your solutions so that others can help you easily
and don’t forget to add the link to the question.

1 Like

The Question is from August Cook-Off.
The link to solution is: https://www.codechef.com/problems/CHEFNWRK

The glitch to your solution was taking input. Your code is expected to take all the inputs. Then you are expected to perform any operation while the break statement was ending process of taking input. So the next input of array is treated as the start of a new test case.

The modified solution is:

#include<bits/stdc++.h>
using namespace std;
int main(){
  int n,k,t;
  cin>>t;
  while(t--){
    cin>>n>>k;
    int a[n];
    int sum=0,ans=0;
    for(int i=0;i<n;i++)
        cin>>a[i];
    for(int i=0;i<n;i++)
    {
      //cin>>a[i];
      sum+=a[i];
      if(a[i]>k)
      {
        ans=-1;
        break;
      }
    //   if(sum==k)
    //   {
    //     ans++;
    //     sum=0;
    //   }
      if(sum>k)
      {
        ans++;
        sum=a[i];
      }
    }
   //
    if(ans==-1)
      cout<<-1<<endl;
    else
    {
       if(sum>0)
      cout<<ans+1<<endl;
      else cout<<ans<<endl;
    }
  }
}
1 Like

thanx man!

I am sorry,will make sure from next time. thanx