Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- // Initial template for C++
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- //User function template in C++
- class Solution
- {
- public:
- //Function to find minimum number of pages.
- bool allocateposs(int barrier,int N,int M,int A[])
- {
- int pages=0;
- int allocate_stud=1;
- for(int i=0;i<N;i++)
- {
- if(barrier<A[i])
- {
- return false;
- }
- if(pages+A[i]>barrier)
- {
- allocate_stud++;
- pages=A[i];
- }
- else
- {
- pages+=A[i];
- }
- }
- if(allocate_stud>M)
- {
- return false;
- }
- return true;
- }
- int findPages(int A[], int N, int M)
- {
- //code here
- int low=A[0];
- int high=0;
- int ans=-1;
- for(int i=0;i<N;i++)
- {
- high+=A[i];
- }
- if(M>N)
- {
- return -1;
- }
- while(low<=high)
- {
- int mid=(low+high)>>1;
- if(allocateposs(mid,N,M,A))
- {
- ans=mid;
- high=mid-1;
- }
- else
- {
- low=mid+1;
- }
- }
- return ans;
- }
- };
- //{ Driver Code Starts.
- int main() {
- int t;
- cin>>t;
- while(t--){
- int n;
- cin>>n;
- int A[n];
- for(int i=0;i<n;i++){
- cin>>A[i];
- }
- int m;
- cin>>m;
- Solution ob;
- cout << ob.findPages(A, n, m) << endl;
- }
- return 0;
- }
- // } Driver Code Ends
- // https://practice.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/
Advertisement
Add Comment
Please, Sign In to add comment