import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = 20;
int m = Integer.parseInt(br.readLine());
int s = 0;
StringBuilder sb = new StringBuilder();
while(m-- > 0) {
String line[] = br.readLine().split(" ");
if(line[0].equals("add")) {
s = (s | (1 << Integer.parseInt(line[1]) - 1));
} else if(line[0].equals("remove")) {
s = (s & ~(1 << Integer.parseInt(line[1]) - 1));
} else if(line[0].equals("check")) {
int res = (s & (1 << Integer.parseInt(line[1]) - 1));
if(res == 0) {
sb.append("0\n");
} else {
sb.append("1\n");
}
} else if(line[0].equals("toggle")) {
s = (s ^ (1 << Integer.parseInt(line[1]) - 1));
} else if(line[0].equals("all")) {
s = (1 << n) - 1;
} else if(line[0].equals("empty")) {
s = 0;
}
}
System.out.print(sb);
}
}
명령문에 따라 적절한 비트연산을 처리해주면 된다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int s = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int answer = 0;
for(int i = 1; i < (1 << n); i++) {
int sum = 0;
for(int k = 0; k < n; k++) {
if((i & (1 << k)) != 0) {
sum += a[k];
}
}
if(sum == s) {
answer += 1;
}
}
System.out.println(answer);
}
}
1부터 전체집합까지 for문을 돌려서 검산을 통해 0이 아닌 경우에 sum 변수에 값을 더해주고 sum이 s인 경우에 answer를 1증가시켜서 경우의 수를 구해주면 된다.