HDU5973 Game of Taking Stones

Two people face two piles of stones and make a game. They take turns to take stones. As game rules, there are two different methods of taking stones: One scheme is that you can take any number of stones in any one pile while the alternative is to take the same amount of stones at the same time in two piles. In the end, the first person taking all the stones is winner.Now,giving the initial number of two stones, can you win this game if you are the first to take stones and both sides have taken the best strategy?

InputInput contains multiple sets of test data.Each test data occupies one line,containing two non-negative integers a andb,representing the number of two stones.a and b are not more than 10^100. OutputFor each test data,output answer on one line.1 means you are the winner,otherwise output 0.

Sample Input

2 1
8 4
4 7

Sample Output

0
1
0

  裸的威佐夫博弈,但问题在于数据范围特别大,只能用Java。但是Java没有开根号的高精度运算,所以用 二分开根号。时间复杂度比较高,正解应该用牛顿迭代法开根号。

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
    public static BigDecimal Get(BigDecimal x) {
        BigDecimal lo = new BigDecimal("0.00000000000000000000000000000");
        BigDecimal hi = x;
        for(int i = 0; i < 1000; i++) {
            BigDecimal mid = lo.add(hi).divide(new BigDecimal("2.0"));
            BigDecimal mid2 = mid.multiply(mid);
            if(mid2.max(x).equals(mid2)) hi = mid;
            else lo = mid;
        }
        return hi;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        BigDecimal n, m;
        BigDecimal sqrt5 = Get(new BigDecimal(5));
        while(in.hasNextBigDecimal()) {
            n = in.nextBigDecimal(); m = in.nextBigDecimal();
            if(m.equals(n.max(m))) {
                BigDecimal x = n;
                n = m;
                m = x;
            }
            BigDecimal k = n.subtract(m);
            BigDecimal p = new BigDecimal(1);
            n = p.add(sqrt5).multiply(k);
            n = n.divide(new BigDecimal(2));
            if(n.toBigInteger().equals(m.toBigInteger())) System.out.println("0");
            else System.out.println("1");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/jinghui_7/article/details/82940318
今日推荐