您的位置:首页 > 理论基础 > 计算机网络

http://acm.hdu.edu.cn/showproblem.php?pid=2446

2010-09-16 20:04 267 查看
/*
*  很水的一个题目,为何给我弄得最后才AC
*  自责ing
*  1 + 1 + 2 + 1 + 2 + 3 + .... = n(n + 1)(n + 2) / 6;
*  二分找最小的n  满足n(n + 1)(n + 2) / 6 >= yy
*  在二分找r(r + 1)/2 <= xx
*  在最大r
*  原来是long 相乘的时候益处了,一直以为是自己的代码写错了
*  zhc说的对,用了BigInteger 干嘛要用long
*  好好练习下java,他们两个都不会的
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int t;
t = cin.nextInt();
while (t-- > 0) {
// BigInteger n;
// n = cin.nextBigInteger();
long n;
n = cin.nextLong();
long lay = Bin(n);
System.out.print(lay + " ");
BigInteger a1 = BigInteger.valueOf(lay - 1);
BigInteger a2 = BigInteger.valueOf(lay);
BigInteger a3 = BigInteger.valueOf(lay + 1);
BigInteger two = BigInteger.valueOf(2);
BigInteger six = BigInteger.valueOf(6);
BigInteger ans = a1.multiply(a2).multiply(a3).divide(six);

BigInteger nn = BigInteger.valueOf(n);
nn = nn.subtract(ans);
long r = Bin2(nn);
//if(r * (r + 1) / 2 == nn.longValue())
//r -= 1;
BigInteger rr = BigInteger.valueOf(r);
if(rr.multiply(rr.add(BigInteger.ONE)).divide(two).compareTo(nn) == 0)
r -= 1;
ans = nn.subtract(BigInteger.valueOf(r).multiply(BigInteger.valueOf(r + 1)).divide(two));
r += 1;
System.out.println(r + " " + ans);
}
}

static long Bin2(BigInteger n) {
BigInteger num = n;
BigInteger two = BigInteger.valueOf(2);
long low = 1;
long high = n.longValue();
long ans = 0;
while (low <= high) {
long mid = (low + high) / 2;
BigInteger a1 = BigInteger.valueOf(mid);
BigInteger a2 = BigInteger.valueOf(mid + 1);
BigInteger sum = a1.multiply(a2);
if (sum.compareTo(num.multiply(two)) == 0) {
return mid;
} else if(sum.compareTo(num.multiply(two)) == -1){
ans = mid ;
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}
static long Bin(long n) {
BigInteger num = BigInteger.valueOf(n);
BigInteger six = BigInteger.valueOf(6);
long low = 1;
long high = (long) Math.sqrt(1.0 * n) + 1;
long ans = 0;
while (low <= high) {
long mid = (low + high) / 2;
BigInteger a1 = BigInteger.valueOf(mid);
BigInteger a2 = BigInteger.valueOf(mid + 1);
BigInteger a3 = BigInteger.valueOf(mid + 2);
BigInteger sum = a1.multiply(a2).multiply(a3);
if (sum.compareTo(num.multiply(six)) == 0) {
//ans = mid;
//high = mid - 1;
return mid;
} else if(sum.compareTo(num.multiply(six)) == 1){
ans = mid ;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  import string class java