Skip to content

Latest commit

Β 

History

History
153 lines (101 loc) Β· 3.05 KB

0720-bitmask.md

File metadata and controls

153 lines (101 loc) Β· 3.05 KB

2020.07.20 Mon

πŸ“šκ³΅λΆ€ν•œ κ±° ListπŸ“š
  • μ’…λ§ŒλΆ - λΉ„νŠΈλ§ˆμŠ€ν¬

λΉ„νŠΈλ§ˆμŠ€ν¬

μ •μ˜ : μ •μˆ˜μ˜ μ΄μ§„μˆ˜ ν‘œν˜„μ„ 자료ꡬ쑰둜 μ“°λŠ” 기법

μ›μ†Œ 20개의 곡집합/꽉 μ°¬ 집합 λ§Œλ“€κΈ°

int emptySet = (1<<20);
int fullSet = (1<<20)-1;

n번째 μ›μ†Œ μΆ”κ°€ν•˜κΈ°/μœ λ¬΄ν™•μΈν•˜κΈ°

elements |= (1<<n);
if(elements & (1<<n))

n번째 μ›μ†Œ μ‚­μ œν•˜κΈ°(1) - μ›λž˜ μžˆλŠ” κ²½μš°μ—λ§Œ

elements -= (1<<n);

n번째 μ›μ†Œ μ‚­μ œν•˜κΈ°(2) - μ›μ†Œμ˜ 유무 상관없이

elements &= ~(1<<n);

ν† κΈ€ν•˜κΈ°(있으면 없도둝, μ—†λ‹€λ©΄ μžˆλ„λ‘ λ§Œλ“€κΈ°)

elements ^= (1<<n);

μ§‘ν•©μ˜ 크기 κ΅¬ν•˜κΈ°

int bitCount(int x) {
  if(x==0) return 0;
  return x%2 + bitCount(x/2);
}

μ§‘ν•©μ—μ„œ κ°€μž₯ μž‘μ€ μ›μ†Œ μ°ΎκΈ° (μ–΄λ”” μžˆλŠ”μ§€) -> 켜져 μžˆλŠ” μ΅œν•˜μœ„ 번호λ₯Ό λ°˜ν™˜ν•˜λ©΄ 됨

int minElement = (elements & -elements);

μ΅œμ†Œ μ›μ†Œ μ§€μš°κΈ°(2의 κ±°λ“­μ œκ³±μΈμ§€ 확인할 λ•Œ μœ μš©ν•˜κ²Œ μ“°μž„)

elements &= (elements-1);

*2의 κ±°λ“­μ œκ³±μ€ μΌœμ§„ λΉ„νŠΈκ°€ 1개 밖에 μ—†λ‹€. 즉, μ΅œν•˜μœ„ λΉ„νŠΈ μ‚­μ œ μ‹œ 전체 값이 0이 λ˜λŠ”μ§€ ν™•μΈν•˜λ©΄ λœλ‹€.

λͺ¨λ“  λΆ€λΆ„ 집합 μˆœνšŒν•˜κΈ°

for(int subset = set; subset; subset = ((subset-1) & set))

subset-1 : μ΅œν•˜μœ„ λΉ„νŠΈλŠ” 끄고, κ·Έ μ•„λž˜ λΉ„νŠΈλŠ” λͺ¨λ‘ μΌœμ§„ μƒνƒœλ‘œ λ§Œλ“ λ‹€.

μ—λΌν† μŠ€ν…Œλ„€μŠ€μ˜ 체

kκ°€ μ†Œμˆ˜μΈμ§€ ν™•μΈν•˜λŠ” ν•¨μˆ˜

inline bool isPrime(int k) {
  return sieve[k>>3] & (1<<(k&7));
}

kκ°€ μ†Œμˆ˜κ°€ μ•„λ‹ˆλΌκ³  ν‘œμ‹œν•˜λŠ” ν•¨μˆ˜ (= μ†Œμˆ˜μ§‘ν•©μ—μ„œ kλ₯Ό μ‚­μ œν•˜λŠ” ν•¨μˆ˜)

inline void setComposite(int k) {
  sieve[k>>3] &= ~(1<<(k&7));
}

15퍼즐

64bit = 4bit * 16

퍼즐의 μƒνƒœλ₯Ό 64λΉ„νŠΈλ‘œ ν‘œν˜„ν•  수 μžˆλ‹€.

64λΉ„νŠΈ μ •μˆ˜ λ³€μˆ˜ μ„ μ–Έ

typedef unsigned long long uint64;

ν•΄λ‹Ή μΈλ±μŠ€μ— μžˆλŠ” 값을 κ΅¬ν•˜λŠ” ν•¨μˆ˜

/* 
 * @param mask [number storing the state of the puzzle]
 * @param index [position to be changed the value]
 */
int get(uint64 mask, int index) {
  return (mask >> (index <<2)) & 15;
}

ν•΄λ‹Ή μΈλ±μŠ€μ— 값을 μ„€μ •ν•˜λŠ” ν•¨μˆ˜

/* 
 * @param mask [number storing the state of the puzzle]
 * @param index [position to be changed the value]
 * @param value [new value of the index]
 */
uint64 set(uint64 mask, int index, uint64 value) {
  return mask & ~(15LL << (index<<2)) | (value << (index<<2));
}

κ·ΉλŒ€ μ•ˆμ • 집합

같이 두면 ν­λ°œν•˜λŠ” λ¬Όμ§ˆλ“€μ΄ μƒμ‘΄ν•˜μ§€ μ•ŠλŠ” 집합을 κ΅¬ν•˜λŠ” 문제

집합에 물질 i와 같이 두면 μ•ˆλ˜λŠ” 물질이 μžˆλŠ”μ§€ ν™•μΈν•˜λŠ” ν•΅μ‹¬μ½”λ“œ

/*
 * set : λ¬Όμ§ˆλ“€μ˜ 집합
 * i : 물질의 인덱슀 κ°’
 * explodes[i] : i와 같이 두면 ν­λ°œν•˜λŠ” λ¬Όμ§ˆλ“€μ˜ 집합
 */
(set & (1<<i)) && (set & explodes[i])