【數論】C049_無法構成的新數(BE)

一、Problem

在這裏插入圖片描述

215

二、Solution

題意:從 22 個數中選 ]0,12]]0, 12] 個數,累加其和爲 sum,要求 sum 不能在給定質數集合中找到。

方法一:BE

  • 不定項選擇太麻煩了,直接枚舉子集個數吧…
  • 剪枝:如果當前選擇狀態的個數超過 12 個,枚舉選擇狀態不再進行…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int binary_enum(int[] a) {
			int res = 0, N = a.length;
			int tot = 1 << N;
			Set<Integer> all = new HashSet<>();
			for (int i = 0; i < tot; i++) {
				int cnt = 0;
				int sum = 0;
				for (int j = 0; j < N; j++) {
					if ((i & (1 << j)) > 0) {
						cnt++;
						sum += a[j];
						if (cnt > 12)
							break;
					}
				}
				if (cnt <= 12)
					all.add(sum);
			}
			return 1695 - all.size();
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			int[] a = {3,5,7,11,13,19,23,29,31,37,41,53,59,61,67,71,97,101,127,197,211,431};
			int res = binary_enum(a);
			System.out.println(res);
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}

複雜度分析

  • 時間複雜度:O(222×N)O(2^{22} × N)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章