Check if all people can vote on two machines | C ++ program to check if all people can vote using two machines within limited time ; Returns true if n people can vote using two machines in x time . ; calculate total sum i . e total time taken by all people ; if total time is less than x then all people can definitely vote hence return true ; sort the vector ; declare a vector presum of same size as that of a and initialize it with 0 ; prefixsum for first element will be element itself ; fill the array ; Set i and j and check if array from i to j - 1 gives sum <= x ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canVote ( vector < int > a , int n , int x ) { int total_sum = 0 ; for ( auto x : a ) { total_sum += x ; } if ( total_sum <= x ) return true ; sort ( a . begin ( ) , a . end ( ) ) ; vector < int > presum ( a . size ( ) , 0 ) ; presum [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < presum . size ( ) ; i ++ ) { presum [ i ] = presum [ i - 1 ] + a [ i ] ; } for ( int i = 0 ; i < presum . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < presum . size ( ) ; j ++ ) { int arr1_sum = ( presum [ i ] + ( total_sum - presum [ j ] ) ) ; if ( ( arr1_sum <= x ) && ( total_sum - arr1_sum ) <= x ) return true ; } } return false ; } int main ( ) { int n = 3 , x = 4 ; vector < int > a = { 2 , 4 , 2 } ; canVote ( a , n , x ) ? cout << " YES STRNEWLINE " : cout << " NO STRNEWLINE " ; return 0 ; }