A. From Hero to Zero
题目链接:http://codeforces.com/contest/1175/problem/A
题目
ou are given an integer n and an integer k
In one step you can do one of the following moves:
decrease n by 1;
divide n by k if n is divisible by k.
For example, if n=27 and k=3 you can do the following steps: 27→26→25→24→8→7→6→2→1→0.
You are asked to calculate the minimum number of steps to reach 0 from n.
input
The first line contains one integer t (1≤t≤100) — the number of queries.
The only line of each query contains two integers n
and k (1≤n≤1018, 2≤k≤1018).
output
For each query print the minimum number of steps to reach 0
from n in single line
Example
intput
2
59 3
1000000000000000000 10
output
8
19
题意
给你两个数n,k,你需要将n每次经过以下两个**步骤之一**从而得到0,输出变换次数:
要么n=n-1,要么将n=n/k(前提n能整除k)。
思路
范围太大,暴力绝对TLE,尝试就是浪费生命!
巧办法:
n%k!=0时,变换的步数就是n%k的值,此时当前n=(n-减掉该步数)
n%k==0时,变换的步数就是1,此时当前n=n/k,
n为0结束,将步数累加输出即可。
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=2e5+7; int main() { int T; cin>>T; while(T--) { ll n, k; cin >> n >> k; ll result = 0; while (n != 0) { ll book = n % k; if (book != 0) { result += book; n = n - book; } else { result += 1; n = n / k; } } cout << result << endl; } return 0; }
原文地址:https://www.cnblogs.com/Vampire6/p/10990374.html