Saturday, 2 May 2015

(DISCRETE BINARY SEARCH) Burning Midnight OIL

One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as  lines, drinks another cup of tea, then he writes  lines and so on: , ...
The expression  is regarded as the integral part from dividing number a by number b.
The moment the current value  equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.
Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep.
Input
The input consists of two integers n and k, separated by spaces — the size of the program in lines and the productivity reduction coefficient, 1 ≤ n ≤ 1092 ≤ k ≤ 10.
Output
Print the only integer — the minimum value of v that lets Vasya write the program in one night.
Sample test(s)
input
7 2
output
4
input
59 9
output
54
Note
In the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task.
In the second sample the answer is v = 54. Vasya writes the code in the following portions: 546. The total sum is 54 + 6 = 60, that's even more than n = 59.

######################EDITYORIAL##################
ITHIS PROCAN BE DONE USING DISCRITE BINARY SEARCH .. LE MIN VALUE BE IN THE RAH=NGE OF 1 TO N SO USING DISCREAT BINARYSEARCH FIND LEAST VALUE OF N FOR WHICH  WE GET SUM =N;
###################################CODE########################
#include<iostream>
#include<bits/stdc++.h>
typedef long long int lli;
using namespace std;
lli  n,k;
lli find(lli start,lli end)
 {

lli ans=INT_MAX;
   //cout<<"start "<<start<<"end "<<end<<endl;
   
     while(start<end)
      {
      lli mid=(start+end)/2;
      //cout<<"mid"<<mid<<endl;
       //cout<<"start "<<start<<"end "<<end<<endl;
      int i=0;
      lli pre=0;
       lli temp=mid;
         while(temp/pow(k,i)>0)
          {
          pre+=temp/pow(k,i);
          
          i++;
          }
      //   cout<<"pre "<<pre<<endl;
          if(pre <n)
           {
           
            start=mid+1;
           }
           else
            {
            if(mid<ans) ans=mid;
             end=mid;
            }
      }
      return ans;
 }
int main()
 {
 
  cin>>n>>k;
  if(n==1  || n<=k) cout<<n<<endl;
  else
  {
  lli ans=find(1,n);
    cout<<ans<<endl;
  }
   
    return 0;
 }

No comments:

Post a Comment