题意:N个数K路归并排序最多需要比较多少次
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new FZU1919().solve();
}
}
class FZU1919 {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
void solve() {
int t = in.nextInt();
for (int ca = 1; ca <= t; ca++) {
dp.clear();
System.out.println("Case " + ca + ": " + dfs(in.nextBigInteger(), in.nextBigInteger()));
}
}
final BigInteger one = BigInteger.ONE;
final BigInteger two = BigInteger.valueOf(2);
final BigInteger zore = BigInteger.ZERO;
Map<BigInteger, BigInteger> dp = new HashMap<BigInteger, BigInteger>();
BigInteger dfs(BigInteger n, BigInteger k) {
if (dp.containsKey(n))
return dp.get(n);
if (n.compareTo(k) <= 0)
return (n.multiply(n.subtract(one))).divide(two);
BigInteger res = zore;
BigInteger m = n.divide(k);
if ((n.mod(k)).compareTo(zore) == 0)
res = res.add(k.multiply(dfs(m, k)));
else {
res = res.add((n.mod(k)).multiply(dfs(m.add(one), k)));
res = res.add((k.subtract(n.mod(k))).multiply(dfs(m, k)));
}
res = res.add((k.multiply(k.subtract(one))).divide(two));
res = res.add((k.subtract(one)).multiply(n.subtract(k)));
dp.put(n, res);
return res;
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}