• 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);
    		}
    	}
    
    }
               
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    必备单词
    Vim
    Linux基础
    python链表操作详解
    冒泡和快速排序
    学员练车选课系统
    面试题
    获取resp:heads:content-disposition的filename
    记录springBoot启动报错(无脑型)
    springBoot+Vue搭建新项目(1)
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/9052595.html
Copyright © 2020-2023  润新知