Codeforces Burning Midnight Oil

qingyezhu發表於2013-10-12
/*
 * BurningMidnightOil.cpp
 *
 *  Created on: 2013-10-12
 *      Author: wangzhu
 */

/**
 * 每次至少寫多少行程式碼ret:
 * 1)、當n<=k時,肯定是ret = n;
 * 2)、當n > k時,則 ret>=k&ret <= n,故只需要按二分的思路將其查詢一下,就可以,
 * 對於每一個可能的值進行計算可以書寫的程式碼行,之後繼續,最後得到的結果就是答案
 */
#include<cstdio>
#include<iostream>
using namespace std;
#define LL long long
LL calc(int k, int v) {
    //資料容易溢位
    LL sum = v, kk = k;
    while (v / kk) {
        sum += v / kk;
        kk *= k;
    }
    return sum;
}
int binarySearch(int n, int k) {
    LL left = k, right = n, mid = -1;
    while (left <= right) {
        mid = left + (right - left) / 2;
        if (n <= calc(k, mid)) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return (int) left;
}
int main() {
    freopen("data.in", "r", stdin);
    int n, k;
    while (~scanf("%d%d", &n, &k)) {
        if(n <= k) {
            printf("%d\n",n);
            continue;
        }

        printf("%d\n", binarySearch(n, k));
    }
    return 0;
}

 

相關文章