FZU1919递归

题意: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());
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值