알고리즘 문제풀이
Swea D3_11822. 부분집합의 합 Python
아크몽
2024. 2. 8. 21:52
# 부분집합 기호 안쓰고 첫 트라이
t = int(input())
for tc in range(1,t+1):
n, k = list(map(int,input().split()))
cnt = 0
for i in range(12-n+1):
if 3 * i + 3 == k:
cnt +=1
print(f'#{tc} {cnt}')
실수한 부분 : n이 3일때로 고정시키고 풀었음(3*i +3)
# 두번째 트라이
t = int(input())
for tc in range(1,t+1):
n, k = list(map(int,input().split()))
cnt = 0
for i in range(1,12-n+2):
sums = 0
for j in range(n):
sums += i + j
if sums == k:
cnt +=1
print(f'#{tc} {cnt}')
안되는 방법 2
비트 연산자 이용해서 풀기 (
arr = list(range(1, 13)) # 1~12
n = len(arr) # 12
t = int(input())
for tc in range(1,t+1):
N, K = map(int,input().split())
ans = 0
for i in range(1,1<<n): # 1 이상 2의 12승 이하
sums, cnt = 0,0
for j in range(n): # 0부터 시작해야하지만 arr은 1부터 시작하기 때문 => 횟수만 가져오겠다.
if i & 1<<j: # 1<<0 1<<1 1<<2 ... 랑 계속 비교해 간다
sums += arr[j]
cnt += 1
if sums == K and cnt==N: # j 문이 돌고나서 부분집합의 합이 k와 같고, 부분집합의 원소의 갯수가 N과 같은지 확인
ans += 1
print(f'#{tc} {ans}')