JAVA大數貪心

來源:互聯網
上載者:User

標籤:必須   分析   大數   mat   []   math   VID   最小   代碼   

 

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

 

JAVA大數貪心

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.