Schedule jobs so that each server gets equal load | CPP program to schedule jobs so that each server gets equal load . ; Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array elements . ; Possibility 1 ; ensuring that all elements of array b are used . ; If a ( i ) already updated to x move to next element in array a . ; Possibility 2 ; Possibility 3 ; Possibility 4 ; If a ( i ) can not be made equal to x even after adding all possible elements from b ( i ) then print - 1. ; check whether all elements of b are used . ; Return the new array element value . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int a [ ] , int b [ ] , int n ) { int i ; long long int s = 0 ; for ( i = 0 ; i < n ; i ++ ) s += ( a [ i ] + b [ i ] ) ; if ( n == 1 ) return a [ 0 ] + b [ 0 ] ; if ( s % n != 0 ) return -1 ; int x = s / n ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > x ) return -1 ; if ( i > 0 ) { a [ i ] += b [ i - 1 ] ; b [ i - 1 ] = 0 ; } if ( a [ i ] == x ) continue ; int y = a [ i ] + b [ i ] ; if ( i + 1 < n ) y += b [ i + 1 ] ; if ( y == x ) { a [ i ] = y ; b [ i ] = b [ i + 1 ] = 0 ; continue ; } if ( a [ i ] + b [ i ] == x ) { a [ i ] += b [ i ] ; b [ i ] = 0 ; continue ; } if ( i + 1 < n && a [ i ] + b [ i + 1 ] == x ) { a [ i ] += b [ i + 1 ] ; b [ i + 1 ] = 0 ; continue ; } return -1 ; } for ( i = 0 ; i < n ; i ++ ) if ( b [ i ] != 0 ) return -1 ; return x ; } int main ( ) { int a [ ] = { 6 , 14 , 21 , 1 } ; int b [ ] = { 15 , 7 , 10 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << solve ( a , b , n ) ; return 0 ; }