Tuesday, 14 July 2015

SPOJ : CANDY 1 solution

EXPLANATION :

This one has a simple way to solve just by using averages.
Calculate the sum of all candies, now if it can be completely 
divided by total no. of packets , i.e remainder of sum/total no. 
of packets , candies can be equally divided into each packet.
Now get the average , and find out the moves.. 

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

int main()
{

    int n,t,sum=0,rem=0,avg=0,total=0;
   
    while(1)
    {
     scanf("%d",&n); // n is no. of packets
     sum=0;
     if(n==-1)   //to end inputting
        break;
     int candy[n];//array for no. of candy in each packets
     for(t=0;t<n;t++)
     {
         scanf("%d",&candy[t]);
         sum+=candy[t];
     }

     rem=sum%n;
     avg=sum/n;
     if(rem != 0)//means it cannot be divided equally
     {
         printf("-1\n");
     }
     else    // else get the total no. of moves by using averages
        {
          total=0;
          for(t=0;t<n;t++)
          {
              if(candy[t]>avg)
                total=total+(candy[t]-avg);
          }
          printf("%d\n",total);
    }//else closed
    }
    return 0;
}

No comments:

Post a Comment

SPOJ : MARBLES Solution

Question  MARBLES - Marbles Explaination.... Fill n spaces , with k colors. First select k spaces with k-different color.  Now we are l...