jayati

Allocate minimum number of pages

Sep 5th, 2023
1,511
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // Initial template for C++
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function template in C++
  10.  
  11. class Solution
  12. {
  13.     public:
  14.     //Function to find minimum number of pages.
  15.     bool allocateposs(int barrier,int N,int M,int A[])
  16.     {
  17.         int pages=0;
  18.         int allocate_stud=1;
  19.         for(int i=0;i<N;i++)
  20.         {
  21.             if(barrier<A[i])
  22.             {
  23.                 return false;
  24.             }
  25.             if(pages+A[i]>barrier)
  26.             {
  27.                 allocate_stud++;
  28.                 pages=A[i];
  29.             }
  30.             else
  31.             {
  32.                 pages+=A[i];
  33.             }
  34.         }
  35.         if(allocate_stud>M)
  36.         {
  37.             return false;
  38.         }
  39.  
  40.       return true;
  41.        
  42.        
  43.     }
  44.     int findPages(int A[], int N, int M)
  45.     {
  46.         //code here
  47.         int low=A[0];
  48.         int high=0;
  49.         int ans=-1;
  50.         for(int i=0;i<N;i++)
  51.         {
  52.             high+=A[i];
  53.         }
  54.         if(M>N)
  55.         {
  56.           return -1;
  57.         }
  58.         while(low<=high)
  59.         {
  60.             int mid=(low+high)>>1;
  61.             if(allocateposs(mid,N,M,A))
  62.             {
  63.                 ans=mid;
  64.                 high=mid-1;
  65.             }
  66.             else
  67.             {
  68.                 low=mid+1;
  69.             }
  70.         }
  71.         return ans;
  72.     }
  73. };
  74.  
  75. //{ Driver Code Starts.
  76.  
  77. int main() {
  78.     int t;
  79.     cin>>t;
  80.     while(t--){
  81.         int n;
  82.         cin>>n;
  83.         int A[n];
  84.         for(int i=0;i<n;i++){
  85.             cin>>A[i];
  86.         }
  87.         int m;
  88.         cin>>m;
  89.         Solution ob;
  90.         cout << ob.findPages(A, n, m) << endl;
  91.     }
  92.     return 0;
  93. }
  94.  
  95. // } Driver Code Ends
  96. // https://practice.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/
Advertisement
Add Comment
Please, Sign In to add comment