B. The Child and Set

 

http://codeforces.com/contest/437/problem/B

 

等差数列1 + 2*k的lowbit()为2^0

等差数列2 + 4*k的lowbit()为2^1

等差数列4 + 8*k的lowbit()为2^2

等差数列8 + 16*k的lowbit()为2^3

 

 1 import java.util.ArrayList;
 2 import java.util.Scanner;
 3 
 4 public class Main {
 5 
 6     public static void main(String[] args) {
 7         Scanner in = new Scanner(System.in);
 8         int sum = in.nextInt(), limit = in.nextInt();
 9 
10         int[] pow = new int[30];pow[0] = 1;
11         for (int i = 1; i < pow.length; i++) pow[i] = pow[i - 1] * 2;
12 
13         int maxbit = Integer.toBinaryString(sum).length();
14         ArrayList<Integer> ans = new ArrayList<>();
15         for (int i = maxbit; i >= -1; i--) {
16             if (i == -1) {
17                 if (sum == 0) {
18                     System.out.println(ans.size());
19                     for (int ii : ans) System.out.print(ii + " ");
20                 } else System.out.println(-1);
21                 return;
22             }
23             for (int j = 0; pow[i] + pow[i + 1] * j <= limit; j++) {
24                 if (sum - pow[i] >= 0) {
25                     sum -= pow[i];
26                     ans.add(pow[i] + pow[i + 1] * j);
27                 }
28             }
29         }
30     }
31 }

 

posted @ 2019-08-24 16:50  dodoBehind  阅读(165)  评论(0编辑  收藏  举报