zoukankan      html  css  js  c++  java
  • JAVA大数贪心

    题意:
    01给出一个数n,现在要将它分为m个数,这m个数相加起来必须等于n,并且要使得这m个数的或值最小。

    思路分析:

    一个简单的贪心,从高位到低位,判断当前位可否为 1 ,若可以,则将所有的数的这一位全部都变成 1

    代码示例:

    import java.math.*;
    import java.util.*;
    
    public class study {
    
    	public static void main(String[] args) {	
    		Scanner cin = new Scanner(System.in);
    		BigInteger n, m;
    		
    		
    		int t = cin.nextInt();
    		for(int cas = 0; cas < t; cas++) {
    			n = cin.nextBigInteger();
    			m = cin.nextBigInteger();
    			BigInteger ans = BigInteger.valueOf(0);
    			
    			int len = 0;
                            BigInteger ss = n, v = BigInteger.valueOf(0);
                            while(ss.compareTo(v)>0){
                                ss = ss.divide(BigInteger.valueOf(2));
                                len++;
                            }    
    			
    			for(int i = len; i >= 0; i--) {
    				BigInteger tem = BigInteger.valueOf(2);
    				tem = tem.pow(i).subtract(BigInteger.valueOf(1)).multiply(m);
    				//System.out.println(tem);
    				if (tem.compareTo(n) < 0) {
    					BigInteger f = BigInteger.valueOf(2).pow(i);
    					ans = ans.add(f);
    					BigInteger p = n.divide(f);
    					if (p.compareTo(m) >= 0) n = n.subtract(m.multiply(f));
    					else n = n.subtract(p.multiply(f));
    					//System.out.println(f);
    					//System.out.println(p);
    				}
    			}
    			System.out.println(ans);
    		}
    	}
    
    }
               
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    主函数main
    static关键字
    this关键字
    构造函数
    封装
    匿名对象
    java基础积累
    JAVA相关知识复习
    ORACLE数据库表空间查询
    两个日期的时间差
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/9052595.html
Copyright © 2011-2022 走看看