NC247579. 牛牛的构造
描述
输入描述
第一行输入两个整数 。 。
输出描述
输出一行,一个长度为 满足条件的数组,两个数之间以一个空格分隔。
示例1
输入:
3 1
输出:
1 3 2
说明:
示例2
输入:
1 100
输出:
-1
Python3 解法, 执行用时: <1ms, 内存消耗: 0K, 提交时间: 2023-08-12 10:13:04
import math n,k=map(int,input().split()) f=[0]*(n+1) f[0]=0 f[1]=0 for i in range(2,n+1): f[i]=int(math.log(i-1,2))+1 count=[1]*(n+1) SUM=sum(f[1:]) if k>SUM: print(-1) else: ret=[] for i in range(n,0,-1): if f[i]<=k: k-=f[i] ret.append(i) count[i]=0 for i in range(1,n+1): if count[i]: ret.append(i) r="" for i in ret: r+=str(i)+" " print(r)
Java 解法, 执行用时: 744ms, 内存消耗: 71308K, 提交时间: 2023-08-12 10:12:41
import java.io.*; import java.util.ArrayList; import java.util.List; public class Main { static final int N = 1000010; static int[] log = new int[N]; static int[] f = new int[N]; static int n, m; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); String[] in = br.readLine().split(" "); n = Integer.parseInt(in[0]); m = Integer.parseInt(in[1]); // log(1) = 0, log(2) = 1, log(4) = 2, log(8) = 3; log[1] = 0; for (int i = 2; i <= n; i++) { log[i] = log[i >> 1] + 1; } for (int i = 2; i <= n; i++) { f[i] = log[i - 1] + 1; } List<Integer> a = new ArrayList<>(); List<Integer> b = new ArrayList<>(); for (int i = n; i >= 1; i--) { if (m >= f[i]) { a.add(i); m -= f[i]; } else { b.add(i); } } if (m != 0) System.out.println("-1"); else { for (int i : a) pw.print(i + " "); for (int i = b.size() - 1; i >= 0; i--) pw.print(b.get(i) + " "); } pw.flush(); } }